The Cascade
Specificity
A CSS declaration that is more specific will take precedence over less specific ones.
First inline styles have the hightest specificity compared to selectors, while each type of selector has its own specificity level.
- ID selectors (most specific selector)
- Class selectors
- Type selectors
Specificity will only be taken into account when an element has multiple, conflicting declarations targeting it, sort of like a tie-breaker.
Note: When there is no declaration with a selector of higher specificity, a rule with a greater number of selectors of the same type will take precedence over another rule with fewer selectors of the same type.
Consider the following HTML and CSS code:
1 | <!-- index.html --> |
1 | /* rule 1 */ |
In the example, both rules are using only class selectors, but the rule 2 is using more class selectors, so it’s more specific
Now let’s change things a bit:
1 | <!-- index.html --> |
1 | /* rule 1 */ |
In this example, despite rule 2 having more class selectors, rule 1 is more specific because ID beats class.
And a bit more complex:
1 | <!-- index.html --> |
1 | /* rule 1 */ |
In this case both rules have only one ID selector, while rule 2 has an additional class selector. So rule 2 has a higher specificity.
Inheritance
Typography-based properties (color
, font-size
, font-family
, etc.) are usually inherited, while most other properties aren’t.
Rule order
After every other factor has been taken into account, there are still multiple conflicting rules targeting an element. Whichever rule was the last defined is the winner.
1 | /* styles.css */ |
In this case, If an element has both the alert
class and the warning
class, the color property will be yellow.