Introduction to Cascade Layers with @layer

The Problem @layer Solves

In a large project, CSS often comes from several sources - a base reset, a third-party component library, and custom project styles. Without cascade layers, overriding a library's style sometimes means fighting its specificity with increasingly specific selectors or reaching for !important, since normal cascade order alone cannot express "this whole group of rules should lose to that whole group," regardless of individual specificity.

Defining Layer Order Up Front

@layer reset, base, components, utilities;

This single line declares the order of layers before any of them are even written - utilities will always win over components, which always wins over base, regardless of specificity or how the styles are later organized across files.

Assigning Styles to a Layer

@layer reset {
  * { margin: 0; padding: 0; }
}

@layer components {
  .btn { padding: 10px 20px; border-radius: 6px; }
}

@layer utilities {
  .p-0 { padding: 0; }
}

Even though .p-0 in the utilities layer has lower specificity than .btn in components, it still wins when both apply to the same element, purely because of layer order - something impossible to guarantee with specificity alone.

Where Unlayered Styles Fit

Any CSS written outside of an @layer block is treated as if it belongs to a final, implicit layer that comes after every named layer - meaning unlayered styles always win over layered ones, regardless of specificity.

The Key Mental Shift

Cascade layers introduce a new, higher-priority rule ahead of specificity: layer order is checked first, and only when two rules are in the exact same layer does specificity decide the winner as before.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.