CSS spec: Cascade Layers — quick introduction and usage examples
References:
https://drafts.csswg.org/css-cascade-5/#layering
https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
https://www.smashingmagazine.com/2022/01/introduction-css-cascade-layers
Supported browsers:
Chrome Canary/Chromium 99+
Firefox Nightly 97+,
Safari Technical Preview 137+
Problem to solve
Unpredictable CSS values after calculation.
Endless battling against regressions from CSS collision:
- Bloated CSS selector complexity to maintain CSS specificity
- Fragile CSS rule ordering caused by CSS selector collision
!important
coming from every place
The goal of CSS Cascade Layer
Cascade layers allow controlling the specificity and order of rule sets across stylesheets, which generates maintainable and predictable CSS values.
When layer presents, layers are first ordered regardless the specificity of CSS rules each of them include.
For example:
@layer base, specific;.p {
color: blue;
}@layer base {
color: red;
}@layer specific {
color: green;
}/* precedence(high > low): .p > specific > base */
/* Any unlayered rule > layered rule unless !important applied */
/* See the end of article for a more complete precedence ordering */
Usages in style file
Usage summarized
- Encapsulate ANY CSS rules
- Easier precedence without relying on sometimes hard to enforce correctly: CSS specificity and rule ordering
- Even works on existing rules
- Augment/override existing layer
- Author can decide if a layer can be override by giving it a name, or not.
Precedence in author-origin
Prior one is overridden by later ones.
- reset layer
- base layer
- patterns layer
- components layer
- unlayered styles (as if they are defined in an un-named layer AFTER ALL layers)
- element-attached
style
attribute - Animations
- Important(
!important
) - Important reset layer
- Important base layer
- Important patterns layer
- Important components layer
- Important unlayered style
- Important element-attached
style
attribute