CSS & Layout

CSS Cascade Layers (@layer)

Native CSS cascade mechanism allowing explicit stylesheet priority ordering before selector specificity is even evaluated.

About this page
READ
2 min
BASELINE
Baseline · Widely available
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
CSS Cascade Resolution with @layer

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#

  • 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.

Where this connects

Prerequisites

Next & related

Security & Accessibility

User Preference Media Queries

Preference media queries override base theme tokens cleanly when structured inside cascade layers.

Mechanical Comparisons