How does CSS specificity work?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Specificity ranks selectors as (inline, id, class/attribute/pseudo-class, element/pseudo-element). Higher tiers beat any number of lower ones; equal specificity falls back to source order. !important overrides everything except another !important later.
Detailed explanation
When multiple rules target an element, specificity decides the winner per-property. Compute as four buckets: inline styles (1000), IDs (100), classes/attributes/pseudo-classes (:hover, [type]) (10), elements/pseudo-elements (::before) (1) — compare bucket by bucket, never sum across tiers (11 classes still lose to one ID... wait, reversed: one ID beats eleven classes because tier beats count). Universal selector adds zero; inherited properties carry none. Equal weight resolves by later-in-source winning. !important escapes normal resolution but creates maintenance traps — reserved mostly for utilities/overrides frameworks. Practical strategy keeps specificity flat and low: single-class selectors everywhere (BEM-style), avoid ID styling entirely, order intentional cascade layers (@layer base < components < utilities in modern CSS) rather than fighting specificity wars. Understanding :where() (zero specificity) and :is() (takes highest argument) rounds out modern control.
Example
#nav .item { } /* 1 ID, 1 class → strong */
.menu li.selected {} /* 2 classes, 1 element */
div {} /* weakest tier */
/* Modern layering beats specificity games: */
@layer base, components, utilities;
@layer components { .btn { color: blue; } }
@layer utilities { .text-red { color: red; } } /* wins regardless */Interview tip
Recite the four buckets crisply, emphasize tier-beats-count with the ID example, then volunteer @layer/:where() as the modern escape from specificity battles.
Common mistakes
- Saying specificity sums numerically across tiers.
- Not knowing source order breaks ties at equal specificity.