What is specificity?
Specificity is the weight the browser gives a selector to decide which rule wins when several rules set the same property on the same element. It is compared as three numbers (IDs, classes/attributes/pseudo-classes, elements/pseudo-elements); the higher value in the first column that differs wins, and only when specificity is equal does the later rule win.
Calculating it (A, B, C)
- A: ID selectors (
#nav). - B: classes, attributes and pseudo-classes (
.btn,[type],:hover). - C: elements and pseudo-elements (
a,::before). - The universal selector
*and combinators add nothing.
Examples:
a= (0,0,1).nav a= (0,1,1).nav a:hover= (0,2,1)#header .nav a= (1,1,1)
Columns never "carry over": one ID (1,0,0) beats any number of classes (0,15,0).
Special cases
- Inline styles beat all selectors;
!importantbeats inline styles. :is()and:not()and:has()take the specificity of their most specific argument.:where()is always zero, which makes it ideal for resets and library defaults.- Cascade layers (
@layer) are checked before specificity: a simple selector in a later layer beats a complex one in an earlier layer.
Avoiding specificity wars
Use mostly single-class selectors, avoid IDs in CSS, keep nesting shallow, and use @layer to order resets, components and utilities instead of escalating to !important.
Code example
1<style>2 body { font-family: system-ui; }3 /* (0,0,1) */ p { color: gray; }4 /* (0,1,1) */ .intro p { color: green; }5 /* (1,0,1) */ #hero p { color: blue; } /* wins: has an ID */6 /* (0,2,1) */ .intro .lead p { color: red; } /* more classes, but loses to the ID */78 /* :where() adds zero specificity, so this is easy to override */9 :where(.btn) { background: #e5e7eb; padding: 6px 12px; border: 0; }10 button { background: #ffd84d; } /* (0,0,1) still wins over :where */1112 /* Layers: order beats specificity */13 @layer base, components;14 @layer components { .tag { color: white; background: #2b4bff; } }15 @layer base { #special.tag { background: gray; } } /* loses: earlier layer */16</style>17<section id="hero" class="intro"><div class="lead"><p>What color am I? (blue)</p></div></section>18<button class="btn">:where() lost to a type selector</button>19<span id="special" class="tag">Layer order wins</span>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.