What does the term "specificity" mean in CSS?
Specificity in CSS is a system of "weights" by which the browser determines which rule is more important when two or more rules match and try to change the same property on the same element.
Put simply: specificity is how precise the selector is. The more precisely a rule targets an element, the higher its priority.
How specificity is calculated (by levels)
From higher weight to lower:
- ID selectors (
#header) - Classes, attributes, pseudo-classes (
.block,[type="text"],:hover) - Tag selectors and pseudo-elements (
div,p,::before)
Inline styles formally rank even above all selectors, but are usually not included in the specificity calculation. And !important sits entirely outside this system and overrides everything.
Comparison example
p { color: blue; } /* tag, low weight */
.text { color: green; } /* class, higher */
#main { color: red; } /* id, highest */The final color will be red, if all selectors apply to the same element.
When specificity decides the outcome
If two rules are equal in level, then order in the code takes over, the one written last wins.
Summary
Specificity is a priority mechanism for CSS selectors. It exists so the browser can unambiguously decide which rule to apply when there are several options.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.