Understanding CSS Specificity

06 February 2013

The topic of css specificity is an important one if you want to write good stylesheets. In this post I’ll try to write the shortest explanation on how the browser calculates what style to apply for an html element.

Why it’s important

If you write stylesheets you often come across situations where the style you are writing doesn’t apply to the element you are trying to style. If it’s not a typo it’s mostly a problem with the css specificity.

Example problem

Let’s say we have this list:

<ul id="things-to-do-before-work">
  <li>wake up</li>
  <li class="coffee">make coffee</li>
  <li>make breakfast</li>
  <li>catch the train</li>
</ul>

And we want to style list item with the class .coffee

#things-to-do-before-work li {
  color: blue;
}
.coffee {
  color: brown;
}

When you switch to the browser you see this list:

So what’s going on? The browser uses certain rules to figure out what style to apply. These rules dictate that the first style rule #things-to-do-before-work li is more important than the last one.

How to calculate to specificity

You can apply styles in four different ways.

Inline styles

<div style="background-color: blue;">I'm blue</div>

With an ID

<div id="some-ID"></div>

With a class or pseudo class

.some-class-name { color: blue; }
.some-class-name:hover { color: brown; }

By styling an element

div { color: brown; }

These types all have a certain number of points per type:

If you add these points together for a style rule you can determine the weight for a rule.

Example calculations

I’ll give you some examples to see how it works in practice:

Style rule: ul#navigation li.coffee a

Total weight: 113 points

Style rule: ul#navigation .coffee a:active

Total weight: 122 points

So in the example above the last rule wins.

Important Notes