Tiffany B. Brown

CSS Tip: Order matters

A while back, I posted a link to Molly Holzschlag’s InformIT article on CSS troubleshooting.

I’ll also add this tip: Order matters.

As Holzschlag explains, style sheets cascade based on a prescribed hierarchy. Local / inline styles override linked and imported styles. And the last linked style sheet overrides style sheets before it.

The same is also true, however, for styles within the same style sheet.

Let’s say you have an HTML document with nested <div>s, and <h2> tags within each <div>, as pictured below:

In this example “Main” and “Right” are our <h2> text (this isn’t a semantically correct example, mind you, just an example). They are also the ids of our <div>. <div id="right"> (in yellow) is a sub-div, if you will, of <div id="main"> (in gray).

Now, in your style sheet, you might have the following code:

#right h2{
color:#96c;
text-decoration:none;
}

#main h2{
color:#00c;
font-size:120%;
text-decoration:underline;
}

However, cascading rules would mean that all of your <h2> text — including what’s in <div id="right"> — would be underlined.

Instead, to get the desired effect, you would need to place the style for <h2> in <div id="right"> after the style for <div id="main"> like so:

#main h2{
color:#00c;
font-size:120%;
text-decoration:underline;
}

#right h2{
color:#96c;
text-decoration:none;
}

Comments are closed.