CSS Cascade Layers (@layer)
Native CSS cascade mechanism allowing explicit stylesheet priority ordering before selector specificity is even evaluated.
About this page
CSS Cascade Resolution with @layer
Observe evaluation order across origins, named layers, and specificity.
@layer reset, base, components; locks in the hierarchy on the first line of CSS.
@layer reset, base, components;- layerOrder
- [ "reset", "base", "components", "(unlayered)" ]
- winner
- Pending
Under the Hood#
- During the
Recalc Stylephase of the Browser Rendering Pipeline, the engine sorts declarations by Origin (User-Agent, User, Author) and then by Layer in declaration order. - Unlayered styles form an implicit anonymous layer with higher priority than all named layers.
- Selector specificity (
#id,.class,[attr]) is only compared between rules within the same layer.
@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+ (
@layerBaseline): Explicit, deterministic layer hierarchy built into CSS Cascade Level 5.
Production Pitfalls#
- Inversion of
!important: Inside@layer, an!importantrule in a lower layer beats an!importantrule 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
Browser Rendering Pipeline (Critical Rendering Path)
Evaluated during the Recalc Style phase when sorting CSSOM declarations.
Next & related
User Preference Media Queries
Preference media queries override base theme tokens cleanly when structured inside cascade layers.
Zero-Runtime Atomic CSS vs Dynamic Style Injection
Atomic CSS compilers emit deterministic @layer rules so utility overrides never depend on stylesheet import order.
Mechanical Comparisons
- Contrasts WithCSS Cascade Layers (@layer) vs CSS Nesting & @scope
@layer orders global stylesheet precedence, whereas @scope bounds selector reach and proximity within a subtree.
- Contrasts WithCSS Cascade Layers (@layer) vs Shadow DOM Encapsulation and Event Retargeting
Cascade Layers organize light-DOM specificity; Shadow DOM creates a hard selector boundary.