CSS Specificity
CSS
What is CSS Specificity?
CSS specificity is a system of weights and ranks used by the browser to decide which CSS rule to apply when multiple rules target the same element.
More specific rules override less specific ones, regardless of where they appear (unless !important is used).
Specificity Value System
Each CSS selector is assigned a specificity score, made of 4 levels (A, B, C, D):
Level | Selector Type | Weight |
---|---|---|
A | Inline styles | 1000 |
B | ID selectors (#id) | 100 |
C | Class, attribute, pseudo-class (.class, [attr], :hover) | 10 |
D | Element and pseudo-elements (div, p, ::before) | 1 |
Example Specificity Scores
The higher the score, the stronger the rule.
- color: orange (inline) wins over red
- #main .text (110) beats .text (10)
- .text (10) beats p (1)
!important Overrides Everything\
This will override all other rules even if their specificity is higher, unless another !important rule is even more specific.
Selector | Specificity |
---|---|
div | 1 |
.class | 10 |
#id | 100 |
style="" | 1000 |
!important | Overrides all |
Tips to Avoid Specificity Issues
- Avoid using too many nested or overly specific selectors
- Use class selectors over IDs for styling
- Use !important only when absolutely necessary