CSS Specificity Explained
Prerequisite — You will need to have a basic knowledge of CSS Selectors.
If there are two or more conflicting CSS rules that target the same DOM element, the browser follows some rules to determine which one is more specific and therefore wins out (gets applied).
In the above code snippet, we have two CSS rules pointing to the same div. But in this case, due to higher specificity (we will discuss in detail what this means below), the 2nd CSS rule wins and background color of the div becomes green.
How to calculate Specificity ?
Let’s now have a look at how to calculate specificity, similar to how the browser does. Higher specificity wins and gets applied.
We will start with a 0 value and add to it based on where the style is written and which CSS selectors are used to reference the DOM element.
- Thousand — Add a 1000 if the declaration is inside a style attribute, aka inline styles.
2. Hundreds — Add a 100 for each ID selector contained inside the overall selector.
3. Tens — Add 10 for each class selector, attribute selector, or pseudo-class contained inside the overall selector.
4. Ones — Add 1 for each element selector or pseudo-element contained inside the overall selector.
The universal selector (*), combinators (+, >, ~, ‘ ‘), and negation pseudo-class (:not) have no effect on specificity. (0 value)
Equal specificity — the latest rule counts
In the above snippet CSS classes green-bg and blue-bg are both applied to the div and have the same specificity (10 each), but the blue-bg class is further down that the green-bg class in declaration. So blue-bg wins and the background-color:blue; is applied to the div.
The !important exception
When an !important rule is used on a style declaration, this declaration overrides any other declarations.
In the above snippet, even though background-color: blue in div would have the least specificity, the use of !important on it overrides all other declarations and the div has a blue background.
If a condition comes where there are two !important styles targeting the same DOM element, then the latest one wins (same as above).
- CSS Specificity calculation — https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#specificity_2
- !important — https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance#!important
Used https://carbon.now.sh/ for the code snippet images.