CSS Constants - Using ID Selectors and Descendent Selectors
(Page 3 of 7 )
Another option to maintain a certain reusability is to make the settings dependent on an ID on the BODY element. First we define the settings applying to all pages:
body{ font-family:Arial,Sans-Serif;
background:#fff;
color:#333;
}
#nav{ width:10em;
margin:0;
padding:.5em;
}
#nav li{ list-style-type:none;
}
h1{ font-size:120%;
border-bottom:1px solid #000;
}
Then we make the colors dependent on the ID of the body:
#home h1{ border-bottom:1px solid #363;
background:#cfc;
}
#home #nav{ border:1px solid #363;
background:#cfc;
}
#contact h1{ border-bottom:1px solid #369;
background:#ccf;
}
#contact #nav{ border:1px solid #369;
background:#ccf;
}
The higher specificity ensures that the original settings get overwritten by the “localized” ones.
Depending on which ID we set on the BODY element, the different color settings get applied, without any need to define classes in the HTML.
While this approach means a lot of repetition in the style sheet, it still -– when properly commented –- provides an easy way to brand different pages differently. All we need to do is add one ID to the BODY of the document, which can be done dynamically on the server or via a content management system.
Both solutions are dependent on changes in the markup though, particularly the classes approach. Real CSS constants shouldn’t need that. To make that happen we have to move away from the browser to the server.
Next: Moving server side >>
More Style Sheets Articles
More By Chris Heilmann