Color scheme

Cascade Layers

In CSS Fundamentals you learned that the cascade resolves competing declarations by checking origin, specificity, and source order. That system works well for small projects, but it starts to crack under pressure once your stylesheet grows or you pull in third party CSS. Cascade layers give you a new, explicit way to group rules so that layer order decides the winner before the browser even looks at specificity. This reading covers how layers work, how to declare them, and how to organize a real project around them.

The Problem Layers Solve

Imagine you are building a site that uses a CSS framework for base components, your own design tokens for theming, and a handful of utility classes for quick overrides. Without layers, every rule from every source lands on the same playing field. The only tools you have to control which rule wins are specificity and source order. That leads to a familiar set of problems: your utility class does not override the framework because the framework selector is more specific, so you bump up your selector or reach for !important, and the cycle repeats. Over time the stylesheet becomes an arms race of increasingly specific selectors.

Cascade layers break this cycle. When you place rules inside a named layer, the browser compares layer order first. A rule in a later layer beats a rule in an earlier layer regardless of how specific either selector is. Specificity still matters, but only as a tiebreaker between rules in the same layer. This means you can write simple, low specificity selectors and still guarantee they win, as long as they live in the right layer.

Declaring Layers and Layer Order

There are three ways to create a cascade layer, and they all use the @layer at-rule. The most important thing to understand is that layer order is set by the order in which layers first appear in your CSS. Once established, that order does not change even if you add more rules to a layer later.

1. Layer Statement (Declaration Only)

The cleanest way to control order is to declare all of your layer names up front in a single statement. This line should be the very first thing in your stylesheet so the order is explicit and easy to find.


        /* Declare order: first layer has lowest priority, last has highest */
        @layer base, components, utilities;
    

No rules go inside this statement. It simply locks in the precedence order. You fill each layer with rules later.

2. Layer Block (Declaration with Rules)

You can also create a layer and add rules at the same time using a block:


        @layer base {
            body {
                font-family: system-ui, sans-serif;
                line-height: 1.6;
            }
        }
    

If the layer already exists (because you declared it earlier), the rules are appended to it. The layer order does not change.

3. Anonymous Layers

If you create a @layer block without a name, it becomes an anonymous layer. Anonymous layers take their position in the order just like named layers, but you can never add rules to them later because there is no name to reference. These are rarely useful in practice, but you should know they exist.


        @layer {
            /* Anonymous: cannot be referenced or appended to later */
            img {
                display: block;
                max-width: 100%;
            }
        }
    

Layer Order Beats Specificity

This is the core idea that makes layers powerful. Once you establish a layer order, a simple class selector in a later layer will override an ID selector in an earlier layer. The demo below lets you toggle between two versions of the same CSS. One version uses no layers, so the higher specificity ID selector wins and the box is red. The other version wraps the rules in layers, and the class in the later layer wins, turning the box green.

Red wins — the ID selector has higher specificity.

                /* Specificity: 1-1-0 (ID + class) */
                #demo .box {
                    background-color: #b91c1c; /* red */
                }

                /* Specificity: 0-1-0 (class only) */
                .box {
                    background-color: #15803d; /* green */
                }

                /* Red wins because 1-1-0 beats 0-1-0 */
            

Without layers, the red rule wins because its selector (#demo .box) has higher specificity than the green rule (.box). With layers, the browser checks layer order first. The green rule lives in the late layer, which was declared after early, so it wins regardless of specificity. Toggle back and forth to see the difference.

Unlayered Styles and !important

Any CSS rule that is not inside a @layer block is considered unlayered. Unlayered styles sit above all named layers in the cascade, which means they always beat layered styles at the same level of importance. This is a deliberate design choice: if you need a one-off override that must win over everything in your layer stack, you can write it outside any layer and it will take priority.

The !important Reversal

Here is where things get counterintuitive. For normal (non-important) declarations, later layers beat earlier layers and unlayered styles beat everything. But when !important is applied, the entire order flips. An !important rule in an early layer beats an !important rule in a late layer, and an !important rule inside any layer beats an !important unlayered rule.

This reversal exists for a good reason. Layers that load first are typically your base and reset styles. If a reset declares box-sizing: border-box !important, it should be very difficult for a later component layer to accidentally override it. The inversion ensures that foundational rules marked as important stay protected.

Avoid !important Anyway

Understanding the reversal is important for reading other people's code, but in your own work you should almost never need !important. If your layers are ordered well, normal declarations in the right layer will do the job.

The full cascade priority for author styles, from lowest to highest, is:

  1. Normal declarations in the first declared layer (lowest priority)
  2. Normal declarations in subsequent layers, in declaration order
  3. Normal unlayered declarations
  4. !important unlayered declarations
  5. !important declarations in the last declared layer
  6. !important declarations in earlier layers, in reverse order (highest priority)

@import with layer()

The @import at-rule has always been a way to pull one stylesheet into another. With cascade layers, you can send an imported file directly into a named layer using the layer() function. This is powerful for file-based architecture because each file lands in its designated layer automatically.


        /* Declare layer order first */
        @layer tokens, base, layout, components, utilities;

        /* Import files into their layers */
        @import url('tokens.css') layer(tokens);
        @import url('base.css') layer(base);
        @import url('layout.css') layer(layout);
        @import url('components.css') layer(components);
        @import url('utilities.css') layer(utilities);
    

The layer declaration at the top locks in the order. Each @import sends its contents into the matching layer. The individual CSS files do not need to know anything about layers; they just contain normal CSS rules. This keeps each file focused on its own concern while the main stylesheet controls precedence.

@import Must Come First

The CSS specification requires that @import rules appear before any other rules in the stylesheet (except @charset and @layer statements). If you put an @import after a regular rule, the browser will ignore it. Always place your layer declaration statement and your imports at the very top of your main stylesheet.

Importing Third Party CSS into a Layer

One of the most practical uses of layered imports is taming third party CSS. If you are using a library or framework, importing it into an early layer ensures that your own styles in later layers will always win, even if the library uses highly specific selectors.


        @layer vendor, tokens, base, components, utilities;

        /* Third party CSS goes in the lowest layer */
        @import url('vendor/normalize.css') layer(vendor);
        @import url('vendor/some-library.css') layer(vendor);

        /* Your styles go in later layers and always win */
        @import url('tokens.css') layer(tokens);
        @import url('components.css') layer(components);
    

This eliminates the need to write increasingly specific selectors or use !important just to override a framework default. The layer order handles it for you.

Avoid Unlayered Styles

Avoid writing unlayered styles unless you genuinely need to override a later layer. If you can write a layered rule that wins, do it. Unlayered styles are a performance and maintainability hazard because they break the predictability of the cascade.

Our Vendor Styles

If you review the source code for this site, you'll notice that we place the vendor layer last. We do this intentionally because our vendor styles are built to inherit from our own CSS tokens (variables) and base styles. This approach keeps vendor components consistent with our design system, which was a consideration when those styles were created. You won't always have this flexibility, but it's a useful idea to keep in mind.

A Practical Layer Stack

There is no single correct set of layer names, but a common pattern that works well for most projects follows this general structure:

  • tokens – Custom properties for colors, spacing, type scale, and other design decisions
  • base – Resets, normalization, and default element styles
  • layout – Page-level structure such as grid areas, sticky headers, and container widths
  • components – Reusable UI patterns like cards, buttons, and navigation
  • utilities – Single-purpose helper classes (visually hidden, text alignment, spacing overrides)
  • vendor – Third party CSS (often placed first so it is easiest to override)

The declaration for this stack might look like:


        @layer vendor, tokens, base, layout, components, utilities;
    

This course site follows exactly this kind of layered architecture. Open your browser DevTools on this page and inspect the stylesheets to see how the layers are organized. Looking at real production CSS that you are already interacting with is one of the best ways to internalize these patterns.

Reuse Your Tokens

When your design tokens live in their own layer as custom properties, every other layer can reference them with var(). This keeps your values consistent and makes theming changes a matter of updating one file. You will explore custom properties and token systems in depth in the custom properties reading.

Debugging When Specificity Still Surprises You

Even with a well organized layer stack, you will occasionally run into a rule that does not apply the way you expect. When that happens, resist the urge to immediately bump up specificity or add !important. Instead, work through a short checklist.

Check Layer Order First

Open DevTools and look at the Styles panel for the element in question. Chrome, Firefox, and Safari all show which layer a rule belongs to. If the rule you want is in an earlier layer than the rule that is winning, layer order is the problem. Move the rule to the correct layer or adjust your layer declaration order.

Check Import Order

If you are using @import with layer(), make sure your imports match the order you declared. A mismatched import can silently create a layer in the wrong position if you forgot to declare it up front.

Then Check Specificity

If both rules are in the same layer, specificity and source order are the tiebreakers, just like traditional CSS. Use the specificity calculation you practiced in CSS Fundamentals to trace the conflict.

Unlayered Rules: Use With Intention

Remember that any rule outside a layer automatically beats all layered rules. If you find that an unlayered rule is winning unexpectedly, either move it into the appropriate layer or keep it unlayered on purpose when you genuinely need it to override everything. Treat unlayered CSS as a deliberate escape hatch rather than a default place to write styles.

Browser Support

Cascade layers are supported in all modern browsers. Chrome and Edge have supported @layer since version 99 (March 2022), Firefox since version 97 (February 2022), and Safari since version 15.4 (March 2022). You do not need to worry about fallbacks for any current browser. If you are curious about the detailed support table, check Can I Use: CSS Cascade Layers.

Resources

The following resources were referenced throughout this reading and are worth bookmarking for future reference.