paulserban.eu

Writing Edition

Paul Serban

Writing, snippets & book notes

Cheat sheet - Post

CSS Cascade Layers (@layer): Explicit Priority Control for CSS

← Back to CSS Layers Explained: Cascade Layers, SOLID Principles, and Design Pattern Analogies

Cascade layers (@layer) let engineers declare that one group of CSS rules is lower priority than another, independent of selector specificity or source order - replacing convention-based specificity management with a browser-enforced mechanism.

Overview

Key Concepts

Layer declaration and priority order

@layer reset, base, components, utilities, overrides;
@layer utilities {
  .text-center { text-align: center; }
}

Specificity still applies - but only within a layer

@layer components, utilities;
@layer components {
  div.card > p.description#intro { text-align: left; } /* loses */
}
@layer utilities {
  .text-center { text-align: center; } /* wins - layer order beats specificity */
}

Unlayered styles and third-party CSS

Layer nesting

Programmatic access via CSSOM

SOLID / GoF analogies

Trade-offs / Caveats

Example in Practice

A realistic design-system entry point composing layers across files:

/* design-system.css - single source of truth for layer ordering */
@layer reset, tokens, base, layout, components, utilities, overrides;
@import url("./reset.css") layer(reset);
@import url("./tokens.css") layer(tokens);
@import url("./components/card.css") layer(components);
@import url("./utilities.css") layer(utilities);
/* tokens.css - low-priority layer; values exist to be referenced, not to win conflicts */
@layer tokens {
  :root { --color-surface: #ffffff; --spacing-md: 1rem; --radius-md: 0.5rem; }
}
/* components/card.css - references tokens; utilities layer can still override */
@layer components {
  .card { background: var(--color-surface); padding: var(--spacing-md); border-radius: var(--radius-md); }
}

Related topics