CSS Specificity Calculator
CSS Selectors can be broken down into different parts and each is worth a different amount of "points" so-to-speak. The overall points a selector has is its specificity.
Specificity is a big determining factor in the cascade which determines which styles will apply to a certain element and which ones won't.
Let's take this selector as an example:
#app .user-list div.user.is-admin a.remove:hover {/* CSS Declarations */}
When two selectors select the same target element, often times we see that the second one wins. But that's not exactly how the rules work. Only if they have the same specificity will the second one win.
These two select the same anchor element in its :hover
state:
/* Specificity: 1,5,2 */#app .user-list div.user.is-admin a.remove:hover {color: #00a9ff;}/* Specificity: 0,5,0 */.user-list .user.is-admin .remove:hover {color: #ec6df1;}
The first one wins in this case and the color
will be this shade of blue (#00a9ff
) because its selector has higher specificity.
How is it determined?
Here's how the points are counted:
- Count the number of IDs. This is the first number.
- Count the number of class, attribute, and pseudo-class selectors. This is the second number
- Count the number of element type and pseudo-elements. This is the third number.
The Cascade
The rules for how CSS determines which CSS wins to stylize an element are referred to as the Cascade.
- If the two rulesets have the same specificity, the later one wins.
- If they have different specificity, the one with the higher specificity wins.
- Inline styles win over any specificity.
These "wins" are on a per-property basis. So even though the first selector has higher specificity, it only "wins" for color
, so the text-decoration
is still applied:
/* Specificity: 1,5,2 */#app .user-list div.user.is-admin a.remove:hover {color: #00a9ff;}/* Specificity: 0,5,0 */.user-list .user.is-admin .remove:hover {text-decoration: underline;color: #ec6df1;}
The ultimate winner is when a property uses !important
. It will win over inline styles and any specificity.
There's more nuance to some of this that we are getting into, so be sure to read more at MDN