Style By Section

I have, for some time now, been using CSS to style sites that I have been working on. I typically use a style sheet named "all.css" to indicate that it is for all pages and all media. I then have a "print.css" for the print media.

Occasionally a site has multiple sections that each have slightly different styles. I typically create an additional style sheet for each section and link to the relevant style sheet conditionally.

This technique works well, but seems wasteful in situations where the styling for each section takes very few lines. I have, in the past, included the relevant styles on directly on each page (avoid this as it is a maintenance nightmare). Ideally, I could include styles for a given section in my primary style sheet and have them only apply to the correct pages automatically. Is such a thing even possible in CSS? Yes! (read on)

First thing's first. How does the browser know which page is in which section? For this, I use the often-ignored body tag. Although rarely used, the body tag (like most other tags) does have "class" and "id" attributes.

In this case, I will use the "class" attribute of the body tag (the "id" attribute would work just as well, but I reserve it for a similar use - more on that in a future post). Simply set the class attribute to the name of the section and then use the cascade to apply your styles to children of a body tag with a style matching that section.

Clear as mud? How about we look at some examples.

Let's say that I have a section called "Careers" (keep in mind that if your section names don't work as a valid CSS class that you will have to modify them so that they do - ditch spaces for example).

<body class="Careers"gt;

Now, I want to style the color of every h2 tag on any page in the careers section (without changing the appearance of h2 in any other section):

body.Careers h2 {color:#9b6340;}

Basically, what this tells the browser is that it should apply the given color (#9b6340) to any h2 tag that is enclosed by a body tag with a class of "Careers".

That's it! Let me know how you make out.

UPDATE (3/06/2005)

This technique can also be used to set current menu state.

BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.