Waterfalls cascading (it's not a perfect metaphor...)

Understanding the Cascade: Part 2 Specificity and Order

15 Jul'13

Part two of Understanding the Cascade details one of the most intriguing (and least understood) concepts of the cascade, CSS specificity as well as the role that rule order plays.

Part two of a three part series on the CSS cascade. You can check out part one of the article (What affects the Cascade and Types of Style sheets) here if you didn't catch it.

Specificity

On top of the type of style sheet, the specificity of the rules are taken into consideration. Consider the following:

#body .header .sidebar .paragraph {color:blue;}
#body #feed {color:purple;}
body div.sidebar p {color:red}
<p style="colour:yellow;">
.header .sidebar p.paragraph {color:green;} 

What colour will the paragraph be?

How specificity is calculated

Each CSS rule receives a 4-part score (0,0,0,0) based on the following:

  1. Inline Style
  2. ID
  3. Classes
  4. elements

Each part of the score beats the next, so elements will always be beaten by classes, classes will always be beaten by IDs and Inline styles will beat all three.

From our example above, the text will be yellow. The full scores are calculated as follows (with the highest specificity at the top):

<p style="colour:yellow;"> (1,0,0,0)

An inline style will beat any number of IDs, classes or elements from a style sheet.

#body #feed {color:purple;} (0,2,0,0)

Two IDs beats the lower single ID, no matter how many classes are present.

#body .header .sidebar .paragraph {color:blue;} (0,1,3,0)

The single ID is enough to beat any number of classes.

.header .sidebar p.paragraph {color:green} (0,0,3,1)

Here three classes beat one class, no matter how many element are included.

body div.sidebar p {color:red} (0,0,1,3)

Order

What if we have the following styles:

#body p {color:blue}
#feed p {color:purple;}

As these both have the same specificity (0,1,0,1), the style that appears the furthest down in the style sheet will win.

Working with multiple style sheets

When working with multiple style sheets, the style sheet included first in the HTML source is given first priority, the sheet included last is given last priority.

Next Up: Part Three

In part three, we'll be looking at how !important declarations affect the cascade and we'll put it all together!


Thanks for stopping by.

Twitter
@tweetbollig
Subscribe via RSS
subscribe
Email
Skype call or chat
chat
Go to top