Specificity on the Web
I've never given much thought to CSS specificity. I guess the cascading aspects of CSS was logical enough to never warrant much investigation.
Lately though, while browsing online, I stumbled upon the MDN post that went into details about CSS specificity. This sparked my curiosity!
When talking about specificity, we're talking about the priority with which styles apply to elements on a HTML page. Not every class, pseudo-class and ID is equal, and the cascading nature of CSS does not decide everything!
Generally speaking, CSS specificity is ranked with 5 values illustrated in the chart below, starting with the CSS rule !important
which has the highest specificity, and ending with the universal CSS selector *{}
which the lowest specificity.
Specificity | Type | Calculated |
---|---|---|
1,0,0,0,0 | !important | 10000 |
0,1,0,0,0 | <style=“”> | 1000 |
0,0,1,0,0 | IDs | 100 |
0,0,0,1,0 | Classes, |
10 |
0,0,0,0,1 | Elements | 1 |
0,0,0,0,0 | * (Universal selector) | 0 |
Or represented visually:
Using a selector like this:
<a href="" class="highlight">Test Link</a>
a.highlight:hover{
background: skyblue;
}
Would net the combined specificity: 0,0,0,2,1
. The class .hightlight
accounts for 0,0,0,1,0
, the pseuod-class :hover
accounts for 0,0,0,1,0
and lastly the element a
accounts for 0,0,0,0,1
, resulting in 0,0,0,2,1
.
This all result in a calculated specificity of 21.
If you were to add an ID to this element, and add styling to the ID:
<a href="" class="highlight" id="link">Test Link</a>
a.highlight:hover{
background: skyblue;
}
#link {
background: dodgerblue;
}
This would override the first selector completely, having a calculated specificity of 100, which vastly outweighs the first selector's 21.