October 2, 2006

CSS 101 - Sequence

Filed under: CSS, Web Design — Douglas T @ 5:52 pm

An aspect of CSS that that I often see overlooked is sequence. The order of your styles can be very important. Web browsers read CSS files from top to bottom, with later styles taking priority over earlier ones. Consider a web page containing the code:

<a href="home">standard link</a>
<div id="control1"><a href="home">link control 1</a>
<div id="control2"><a href="home">link control 2</a>
</div></div>

This hypothetical web page containing the div “control2″ nested within the div “control1″ is using CSS containing these styles:

#control2 a {color:#000000;}
#control1 a {color:#660000;}
a {color:#FFFFFF;}

At first glance, this looks straight forward. Standard links are white (#FFFFFF), control1 links are maroon (#660000), and control2 links are black (#000000). Except if you tried this experiment as shown, it wouldn’t work. Both control1 and control2 links would be maroon. In the order the styles have been placed, the style #control1 follows #control2, and takes priority over it. This problem can be resolved by simply reordering the styles:

a {color:#FFFFFF;}
#control1 a {color:#660000;}
#control2 a {color:#000000;}

For clarity I’ve put the default style first, but the important part of this demonstration is the next two lines. #control1 above #control2. Because #control2 is an exception to #control1, it needs to be below it in the CSS sequence. Think of it this way, each style is a rule which can be modified only by rules that follow it. The default link style “a” is defined as having white links. Then there is an exception to this rule, #control1 links are maroon. Then an exception to that rule is made and #control2 links are made black. In this example, the proper sequence is everything. In the wrong order, the style #control2 is never seen, but always overwritten by #control1. In the proper order, each style is reflected in the appropriate links.

1 Comment »

  1. [...] other problem areas I see I have covered before in other writing. They are Selectors and Sequence. Taking the time to learn a basic understanding of these two last concepts will go a long way [...]

    Pingback by Thoughts on Design » Common CSS problems — February 6, 2007 @ 10:02 am

RSS feed for comments on this post. TrackBack URI

Leave a comment