Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Creating different CSS styles using the body tag

Posted on by Clive Walker in CSS

I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.

It’s sometimes useful to have different styles for the same element on different website pages. Perhaps to highlight a particular aspect of the page. Well, CSS provides a neat way to do this. For example, the navigation tags (above right) are highlighted differently depending on the section of the website.

This effect is achieved relatively simply by assigning an id to the <body> tag of your webpage – like this:

<body id="home">

Then, use the id to create a style (in your stylesheet) that is applicable to all pages with the body id of ‘home’.

Thus, in a simple example, we could use a style rule like this:

body#home p { color: #69C; }

In this case, we use a style rule to create blue paragraphs on any page with a body id of ‘home’. The body id part (identifier) is shown in bold but is always the first part of the style rule.

A slightly more complex example, in our case we have this in our stylesheet:

body#home li.home a:link {
color: #FFF;
background-color: #69C;
}

This rule applies a background colour of #69C and a white text color to <a> links in any <li> item with a class of ‘home’ in any page with a body id of ‘home’. The body id reference is again bolded.

The basic concept is the same as our simple example. To reference the <body> id using a specific style rule. This rule will then only apply to a page with a body id of ‘home’.

Does your site run on Perch CMS? Hire me to help. Perch CMS Development

Comments

  • 08 Jan 2009 15:52:38

    Good tip, but do you think we should precede elements with body#home all the time, or strictly when we have a situation such as that?

    I work in a corp where once you set-up your style sheet you can’t easily go back and make changes so I’m debating using that as a safeguard and putting it in by default all the time.

  • 08 Jan 2009 17:22:57

    I only precede elements with body#home when I need to [in order to keep the style sheets as small as possible] but I don’t have much experience of working on shared or company style sheets. Alternatively, you could certainly add comments to your style sheets as a form of ‘safeguard’ to make them easier to understand for subsequent authors.

Comments are OFF for this post.

© 2024 Clive Walker