How can I count the rule specificity in CSS? I know the basic things (1000 for style, 100 for id, 10 for att/class, etc.) However, I still get stuck too many times with simple things, example:
How much would this be?
<div class="wrapper">
<div class="inner"></div>
</div>
.wrapper > div /* ??? */
.inner /* 10 */
The first rule is applied, obviously. But how much is it?
Basically, it's like this:
!important
styles always override all other styles, but amongst !important
styles, specificity rules do apply*
and inherited styles gets no specificity points.Also, this site might be useful for you. It explains it a bit further.
After testing these rules for myself, I've noticed that this is not exactly true. The order in which the specificity is applied does still hold true, but going by this test, it is not true that it actually works with this points system like most sites I know claim. What seems to be more accurate is putting the styles in "boxes". It would still use the order of "boxes" I listed above, but instead count each "box", and if there is an equal amount of selectors in that group, check the next one. It would then work like this:
!important
styles are in box 1. These styles override all other styles. If there are multiple declarations of the same style that both have the !important
rule, then the style in the next highest box will be looked at.So basically, if we have a style with 1 id selector at the top of our stylesheet, and below that a style with more than 10 class selectors, the style with the id selector will still apply. The style with the id selector "won the battle" in box 3, so the further boxes are ignored. The specificity calculator Fabrício Matté linked to illustrates really well.
PS: using +
or >
or ~
or any other operator won't affect specificity at all. These styles have exactly as much specificity (so the latter will apply):
div > span {color:red;}
div span {color:blue;}