CSS & LayoutBaseline · Widely

CSS Specificity & Inheritance

Mental Model

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.

Interactive Simulator

Cascade & Inheritance Resolution Order

Step through how the style engine picks a winning declaration.

@layer
(A, B, C)
Source Order
Inheritance
Step 1 / 3: 1. Origin & @layer Precedence

Author unlayered rules beat all @layer rules; !important reverses layer order.

@layer base { #nav .link { color: red; } }
Internal State / Memory
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.

  1. Layer Gate: Declarations inside a lower @layer lose to higher layers or unlayered rules before specificity is even compared.
  2. Tuple Comparison: A counts #id selectors; B counts .class, [attr], and :hover; C counts div and ::before. :where() contributes (0, 0, 0), while :is(), :not(), and :has() take the highest specificity in their argument list.
  3. Inheritance: Properties like color, font-family, and CSS Custom Properties copy from the parent's ComputedStyle only if no rule (not even a user-agent rule) targets the element.
CSS
/* 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 .class selectors and !important wars turned large stylesheets into append-only deadlocks.
  • 2020–2022: :where() (zero specificity) and @layer gave design systems deterministic override boundaries.

Production Pitfalls

Production Pitfall
  • :is() specificity surprise: :is(#header, .nav) a gives all matches (even .nav a) the #header specificity of (1, 0, 1).
  • Form control inheritance: <button> and <input> have user-agent font and color rules, blocking <body> inheritance unless inherit is set.
When Not to Use
  • When not to use #id selectors in CSS: Never style with #id selectors in reusable components; reserve #id for DOM anchors and ARIA labelledby targets.

Connections & Logical Next Steps

Mechanical Comparisons