Tiffany B. Brown

18 December 2007

'Namespace' your <body> tags

Posted on: 18 December 2007 at 4:00 am Tags: html, css Slug: namespace-your-body-tags Authors: Tiffany B. Brown

Lately, I’ve been using specificity, inheritance and ‘The Cascade’ to my advantage by adding an id to the <body> tag of every page. This id acts as a namespace of sorts, allowing you to assign page or section-specific style sheets.

It’s a technique I’ve employed on smaller, static sites. But it would work at least as well on complex sites with differing content layouts, or with content management and templating systems that generate category identifiers.

I start by defining global styles common to all pages on the site. For example:

   background: #fff;
   color: #606;
   font: 75% / 1.5 arial, helvetica, sans-serif;

    color: #c09;
    font-family: Georgia;   

Then I use what I’ll call compound selectors to set page- or section-level styles. For example:

body#aboutUs h1{
    font-family: 'Lucida Grande';

I find that by using this technique my CSS becomes far more organized, and my HTML requires far fewer class and id names. I can group page and section specific styles together making them easier to find and read at a glance.

An added benefit is that you have another ‘hook’ in your document for CSS or DOM scripting.