CSS Specificity & Inheritance
CSS does not merge rules by file proximity; it sorts matched declarations by Origin, Cascade Layers, (A, B, C) specificity, and source order. Inheritance only kicks in when zero rules match a property on the element itself.
Cascade & Inheritance Resolution Order
Step through how the style engine picks a winning declaration.
Author unlayered rules beat all @layer rules; !important reverses layer order.
@layer base { #nav .link { color: red; } }- origin
- author
- layer
- base
- specificity
- (1, 1, 0)
Under the Hood
Specificity is a three-digit odometer (IDs, Classes, Tags) where ten Classes never roll over to beat one ID.
- Layer Gate: Declarations inside a lower
@layerlose to higher layers or unlayered rules before specificity is even compared. - Tuple Comparison:
Acounts#idselectors;Bcounts.class,[attr], and:hover;Ccountsdivand::before.:where()contributes(0, 0, 0), while:is(),:not(), and :has() take the highest specificity in their argument list. - Inheritance: Properties like
color,font-family, and CSS Custom Properties copy from the parent'sComputedStyleonly if no rule (not even a user-agent rule) targets the element.
/* Zero specificity reset: trivial to override anywhere */
:where(button, input, select) {
font: inherit;
color: inherit;
}
/* Specificity (0, 1, 0) beats (0, 0, 1) regardless of order */
.btn-primary { background: #2563eb; }Problem Genealogy
- 1998–2018: Escalating
#id .classselectors and!importantwars turned large stylesheets into append-only deadlocks. - 2020–2022:
:where()(zero specificity) and@layergave design systems deterministic override boundaries.
Production Pitfalls
:is()specificity surprise::is(#header, .nav) agives all matches (even.nav a) the#headerspecificity of(1, 0, 1).- Form control inheritance:
<button>and<input>have user-agentfontandcolorrules, blocking<body>inheritance unlessinheritis set.
- When not to use
#idselectors in CSS: Never style with#idselectors in reusable components; reserve#idfor DOM anchors and ARIAlabelledbytargets.
Connections & Logical Next Steps
Custom properties participate in the standard cascade and inherit down DOM descendants.
:has() inherits the highest specificity among its relative selector arguments.
Native nesting wraps parent selectors in :is(), inheriting their highest specificity.
Cascade Layers evaluate before selector specificity (A, B, C) tuples.
Selector specificity arbitrates competing rule declarations, whereas custom properties inherit down the DOM tree.
:has() adopts the highest specificity of its relative selector list instead of summing combinators.
Mechanical Comparisons
Selector specificity arbitrates competing rule declarations, whereas custom properties inherit down the DOM tree.
:has() adopts the highest specificity of its relative selector list instead of summing combinators.