Codectionary / Developer documentation / CSS

Cascade Layers (@layer)

@layer lets you explicitly define the priority order between groups of CSS rules, independent of selector specificity. Styles in a layer declared later always beat styles in an earlier layer, regardless of how specific the earlier layer's selectors are - solving specificity conflicts between resets, frameworks, components, and overrides in a predictable, structured way.

Syntax

@layer name { }
@layer layer1, layer2, layer3;

Examples

Declaring Layer Order

Establishing which layers should win, before any of them are even defined.

@layer reset, base, components, utilities;
/* utilities will always beat components, which always beats base, etc,
   regardless of specificity, since layer order is declared upfront */

Layers Beating Specificity

A low-specificity rule in a later layer wins over a high-specificity rule in an earlier layer.

@layer base {
  #card.featured.active { color: red; } /* very high specificity */
}

@layer utilities {
  .text-blue { color: blue; } /* much lower specificity, but wins - later layer */
}
/* Without @layer, the #id-based rule in base would normally win despite coming first */

Parameters and values

  • @layer name { } (at-rule): Defines a named cascade layer and its rules
  • @layer a, b, c; (at-rule): Declares layer priority order upfront, without defining rules yet

Best practices

  • Declare your full layer order upfront with @layer name1, name2, name3; even before writing rules, so the priority is clear from the start of the stylesheet
  • Use layers to cleanly separate resets, base styles, component styles, and utility overrides - a common structure that eliminates most specificity conflicts
  • Remember unlayered styles (written outside any @layer) always beat layered styles, regardless of layer order - keep genuinely critical overrides unlayered intentionally
  • This replaces many of the reasons teams historically reached for !important - a properly layered stylesheet rarely needs it

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation