Specificity is the set of rules applied by browsers to determine which CSS property values are the most relevant to an element and, therefore, will be applied.
Specificity is based on matching rules which are composed of different CSS selectors. The hierarchy, from highest to lowest, is:
style="color:red")#header).nav, [type="text"], :hover)h1, p, ::before)In simple terms, think of it as a score (0, 0, 0, 0):
| Selector | Score (Thousands, Hundreds, Tens, Ones) |
|---|---|
| Inline Style | 1, 0, 0, 0 |
| ID Selector (e.g. #test) | 0, 1, 0, 0 |
| Class / Attribute / Pseudo-class | 0, 0, 1, 0 |
| Element / Pseudo-element | 0, 0, 0, 1 |
Assume we have these three rules targeting the same <p> element:
p { color: grey; } /* Specificity 0,0,0,1 */
.intro { color: blue; } /* Specificity 0,0,1,0 (WINS!) */
#main p { color: green; } /* Specificity 0,1,0,1 (OVERALL WINNER!) */
*) and combinators (+, >, ~) have zero specificity.