CSS – Cascading Style Sheets – somethink, that is used by big part of frontend developers. But even this, I met programmers, that have used CSS by years, and still have thinked, that style on the end of sheet overrides this on the beggining.
<p id="a" class="b">Some text </p>
<style>
.b{
color:red;
}
#a{
color:green;
}
p{
color:blue;
}
</style>
Cascading is set of rules which styles overrides which. On the example above we have a color defined 3 times, but at the end Some Text will be green.
The most importent (it means overriding others) are styles with !improtant, but using it should be treated as a last resort. Second are inline styles <p style=”color:red”>. Next are style sheets, and on the end default browser styles.
When there are multiple styles in style sheet, there are compared by specificity, and only, when specificities are equat, an order matters.
A specificity is a scoring, how each selector is specific, with an assumption, that more specific selector overrides thes more general. It is compound with 3 numbers: count of IDs, classes and types.
For example, #a{color:green} has a specificity 1,0,0, becouse it has got one id, 0 classes and 0 types. An ID is meat to indicate one element, so styles with ID overrides these without it.
.b{color:red;} is a class selector, so it has a specificity 0,1,0. Also attribute selectors (for example [alt=””]) and pseudoclasses (for evample :hover) are treated as equal to classes.
p {color:blue;} is a type selector, so it has a specificity 0,0,1. Also pseudoelements (for example ::before) are treated as types.
The most general selectors like * has a specificity 0,0,0.
A specificity as added, so for example .classA.classB.classC has specificity 0,3,0. Also when we join multiple kinds of selector specificity is added, like in html > body > .a.b.c we have a specificity 0,3,2 (0 ids, 3 classes and 2 types).
You should be carrefould with :not(), becouse it not changes specificity by itself, but selector inside are added, so div:not(#someID) has a specificity 1,0,1. It can be also treated as trick how to bust a specificity, by simpli using ID or class that doesn’t exist :not(#dummyID).
Only on the end, when we have more than one selector with the same specificity, an order in code matters.
One thought on “[en] Specificity: what means C in CSS”