CSS spec: Cascade Layers — quick introduction and usage examples

Nate Liu
2 min readMar 5, 2022
Photo by Clark Van Der Beken on Unsplash

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

  1. Encapsulate ANY CSS rules
  2. Easier precedence without relying on sometimes hard to enforce correctly: CSS specificity and rule ordering
  3. Even works on existing rules
  4. Augment/override existing layer
  5. 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.

  1. reset layer
  2. base layer
  3. patterns layer
  4. components layer
  5. unlayered styles (as if they are defined in an un-named layer AFTER ALL layers)
  6. element-attached style attribute
  7. Animations
  8. Important(!important)
  9. Important reset layer
  10. Important base layer
  11. Important patterns layer
  12. Important components layer
  13. Important unlayered style
  14. Important element-attached style attribute

--

--

Nate Liu

Passionate engineer, UX advocator and snow chaser.