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.
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.
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.
You can apply styles in four different ways.
<div style="background-color: blue;">I'm blue</div>
<div id="some-ID"></div>
.some-class-name { color: blue; }
.some-class-name:hover { color: brown; }
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.
I’ll give you some examples to see how it works in practice:
Style rule: ul#navigation li.coffee a
#navigation
).coffee
)ul
,li
,a
)Total weight: 113 points
Style rule: ul#navigation .coffee a:active
#navigation
).coffee
, :active
)ul
,a
)Total weight: 122 points
So in the example above the last rule wins.
!important
is an automatic win*
gets no points:first-line
) get 1 point unlike their psuedo-class brothers which get 10 pointsLike this post? Follow me at @jankeesvw on Twitter