CSS & LayoutBaseline · Widely

CSS Cascade Layers (@layer)

Mental Model

@layer places layer priority above selector specificity in the CSS cascade algorithm. An #id selector inside a lower layer loses to a plain .btn class inside a higher layer.

Interactive Simulator

CSS Cascade Resolution with @layer

Observe evaluation order across origins, named layers, and specificity.

Step 1 / 3: 1. Declaring Layer Order

@layer reset, base, components; locks in the hierarchy on the first line of CSS.

@layer reset, base, components;
Internal State / Memory
layerOrder
[ "reset", "base", "components", "(unlayered)" ]
winner
Pending

Under the Hood

  1. During the Recalc Style phase of the Browser Rendering Pipeline, the engine sorts declarations by Origin (User-Agent, User, Author) and then by Layer in declaration order.
  2. Unlayered styles form an implicit anonymous layer with higher priority than all named layers.
  3. Selector specificity (#id, .class, [attr]) is only compared between rules within the same layer.
CSS
@layer reset, components, utilities;

@layer components {
  /* Higher specificity (1, 1, 0), lower layer -> LOSES */
  #checkout .btn-primary { background: #1e293b; }
}

@layer utilities {
  /* Lower specificity (0, 1, 0), higher layer -> WINS */
  .bg-sky { background: #0284c7; }
}

Problem Genealogy

  • 2013 (BEM & ITCSS): Manual naming conventions to keep all selectors at flat (0,1,0) specificity, which worked until a single third-party widget arrived with #widget .btn.
  • 2019 (Escalating !important): Specificity wars between resets, CSS frameworks, and local overrides.
  • 2022+ (@layer Baseline): Explicit, deterministic layer hierarchy built into CSS Cascade Level 5.

Production Pitfalls

Production Pitfall
  • Inversion of !important: Inside @layer, an !important rule in a lower layer beats an !important rule in a higher layer (reversed by the spec to protect base invariants).
  • Unlayered third-party styles: Importing a library without layer(...) places it in the final anonymous layer, overriding your named layers, just like an unlayered global CSS rule leaking past CSS Container Queries overrides.
When Not to Use
  • When not to use @layer: Inside a strictly isolated Shadow DOM or CSS Nesting & @scope component without competing global stylesheets, @layer adds unnecessary indirection.

Connections & Logical Next Steps

Mechanical Comparisons