How is specificity calculated? What does the specificity formula look like?
Specificity is calculated as a numeric "weight" of the selector, made up of four digits. The browser builds the number using the formula:
javascript
[a, b, c, d]Where:
| Digit | What it counts | Examples |
|---|---|---|
| a | inline styles | style="" |
| b | ID selectors | #header |
| c | classes, attributes, pseudo-classes | .box, [type="text"], :hover |
| d | tag selectors and pseudo-elements | div, p, ::after |
How it's calculated
The selector is broken down into parts, and each part increases one of the digits.
For example:
| Selector | Specificity |
|---|---|
div | 0,0,0,1 |
.text | 0,0,1,0 |
#main | 0,1,0,0 |
header .menu li | 0,0,1,2 (1 class + 2 tags) |
#main .menu li | 0,1,1,1 |
style="color:red" | 1,0,0,0 |
How they're compared
The comparison goes digit by digit, from left to right:
- first
a(inline) is compared - if equal,
b(id) - if equal,
c(classes) - if equal,
d(tags)
The rule with the higher number in the first digit that differs is the one that applies.
Important exceptions
!importantdoes not take part in the formula, but overrides everything except another!important*(the universal selector) adds no weight- combinators (
>,+,~, a space) also do not affect the weight
Summary of the formula
Specificity = [a, b, c, d], where:
a: inlineb: IDc: classes, attributes, pseudo-classesd: tags and pseudo-elements
This formula determines which rule wins when styles conflict.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.