What is selector specificity and how is it calculated?
Specificity is the weight CSS gives a selector to decide which rule wins when several target the same element; more specific selectors beat less specific ones.
It is the second tie-breaker in the cascade (after !important, before source order). The weight is counted in four buckets, conventionally written (A, B, C, D) from most to least powerful:
- A — inline styles (a
style="..."attribute) - B — the number of id selectors
- C — the number of class selectors, attribute selectors and pseudo-classes
- D — the number of element (tag) selectors and pseudo-elements
Compare the buckets left to right: a single id (B) outranks any number of classes (C), which outrank any number of tags (D). Some examples:
p /* 0,0,0,1 */
.class /* 0,0,1,0 - beats the bare p */
p.class /* 0,0,1,1 */
#id /* 0,1,0,0 - beats anything class-based */
#id .class p /* 0,1,1,1 */
/* style="..." -> 1,0,0,0 - beats any selector */
The resolution rules:
- Higher specificity always wins.
- Equal specificity → the rule written later wins.
!importantoverrides all of the above (and only another!importantcan beat it).
The practical advice is to keep specificity low and even — lean on classes and avoid styling with ids — so that overriding a rule later is a matter of a small, predictable bump rather than an arms race.
Go deeper:
Specificity (MDN) — the canonical reference for the three/four-column weighting, including how
:is(),:not(), and:where()count.Specificity Calculator (keegan.st) — paste any selector and see its weight broken down visually.
Specifics on CSS Specificity (CSS-Tricks) — a friendly walk-through with diagrams of how the points add up.
Cascading Style Sheets (Wikipedia) — specificity examples and tables in the broader context of the cascade.