Cascade Layers in CSS by kirupa (https://www.kirupa.com/me/index.htm) | filed under HTML and CSS (https://www.kirupa.com/html5/learn_html_css.htm) TL;DR: Cascade layers let us group styles and decide which group wins before specificity is even considered. We declare the order with @layer reset, base, library, theme; and a rule in a later layer beats a more specific rule in an earlier one. Unlayered styles beat every layer, and !important reverses the order. - The first time a layer is named sets its place, so one @layer statement at the top of our CSS locks in the order. - A plain .btn rule in a later layer beats #shop .btn in an earlier layer, because the browser checks layers before specificity. - Putting resets and third-party CSS into low layers, even with @import layer(), keeps our own styles in charge. - For !important declarations, earlier layers win, which lets a reset protect essentials like [hidden] staying hidden. Every CSS developer has lived through this. We pull a component library into our page, and we write a perfectly reasonable rule to make its button yellow. Nothing happens. The library's rule uses an ID somewhere in its selector, so it outranks ours, and the button stays stubbornly blue. So we add an ID of our own, or a second class, or the dreaded !important, and the next person who touches this code has to escalate even further. Modern CSS gives us a way out of that arms race. Instead of fighting over which selector is heavier, we can decide up front which group of styles should win. Here is a button caught between a library's styles and ours, and you get to pick the winner: Live demo: A Buy now button styled by two rules: a blue #shop .btn rule in a library layer and a yellow .btn rule in a theme layer. A list shows the layers from lowest to highest priority and marks which one wins. Radio buttons switch the layer order, and a checkbox loads the library outside any layer (https://www.kirupa.com/html5/examples/cascade_layers_button.htm) Try it: 1. Pick @layer reset, theme, library; and watch the button turn blue 2. Switch back, then check Load the library outside any layer The library's selector is more specific than ours the entire time, and it still loses whenever our styles sit in a later group. In this tutorial, we'll look at how those groups work, why their order matters more than specificity, and where !important fits in. Onwards! What Problem Do Cascade Layers Solve? Let's look at the two rules behind our button. The library styles every button inside its shop with this rule: #shop .btn { background-color: #0798ff; color: #ffffff; } Our own styles want every button to be yellow, so we wrote this rule, and we made sure it comes after the library's stylesheet: .btn { background-color: #ffe561; color: #1e2933; } When two rules set the same property on the same element, the browser has to pick one. One of the things it compares is specificity (https://www.kirupa.com/html5/css_selectors_type_class_id.htm), a score based on how many IDs, classes, and element names a selector has. The library's selector has one ID and one class. Ours has just one class. An ID outweighs any number of classes, so the library wins, and the fact that our rule comes later in the file doesn't matter. Order of appearance only breaks a tie when the specificity is exactly the same. To win the old way, we'd have to out-specific the library with something like #shop .btn.btn, or slap !important on our declarations. Both work today and both make tomorrow worse, because the next override has to beat those. What we really want is to tell the browser, "Everything from the library is a default. Everything from our theme should win over it, no matter how the selectors are written." That's what cascade layers let us do. How Do We Create Layers? A cascade layer is a named group of styles. We create one with the @layer rule, give it a name, and put style rules inside its block: @layer library { #shop .btn { background-color: #0798ff; color: #ffffff; } } @layer theme { .btn { background-color: #ffe561; color: #1e2933; } } The order of our layers is set by the first time each name shows up. Here, library appears first and theme second, so theme has the higher priority. Relying on where blocks happen to show up gets fragile once styles are spread across several files, so it's common to declare the order on its own at the very top of our CSS: @layer reset, base, library, theme; This one line creates four empty layers and locks in their order. Any @layer block we write later, in any file, adds its rules to one of these layers without changing where that layer sits in line: [Image: The statement @layer reset, base, library, theme; creates four layers. They stack from the bottom up in that order: reset has the lowest priority, then base, then library, then theme. A dashed box for unlayered styles sits on top of all four. An arrow on the left runs from Loses at the bottom to Wins at the top, and a callout points at reset as the layer that was named first.] (https://www.kirupa.com/html5/images/layers_stack.png) The layer we named first sits at the bottom of the stack and has the lowest priority. Each layer after it sits a step higher. Sitting on top of all of them are the styles that aren't in any layer, and we'll come back to those in a bit. We can also put a whole stylesheet into a layer as we import it. This is a great fit for third-party CSS that we don't want to edit: @import url("library.css") layer(library); Why Does a Later Layer Beat a More Specific Selector? When the browser has two competing declarations, it asks a series of questions in a fixed order, and it stops at the first question that has a clear answer. Cascade layers are one of those questions, and they are asked before specificity: [Image: The questions the browser asks, in order, when two rules set the same property: 1 origin and importance, 2 context (shadow DOM), 3 inline style attribute, 4 cascade layers, 5 specificity, and 6 order of appearance. Cascade layers is highlighted, and a callout says it comes before specificity.] (https://www.kirupa.com/html5/images/layers_cascade_steps.png) Our two button rules come from the same stylesheet, live in the same document, and neither one is an inline style attribute. So the first three questions end in a tie, and the browser moves on to layers. The library's rule is in the library layer, and ours is in the later theme layer. Ours wins right there, and the browser never even looks at specificity: [Image: Two rules style the same Buy now button. In the library layer, #shop .btn scores 1 ID, 1 class, and 0 types and sets a blue background. In the theme layer, .btn scores 0 IDs, 1 class, and 0 types and sets a yellow background. The button ends up yellow, and a callout says the later layer wins.] (https://www.kirupa.com/html5/images/layers_button_fight.png) The library's selector is still heavier, with a score of (1, 1, 0) against our (0, 1, 0). It doesn't matter, because specificity only gets a say when two rules are in the same layer. If you go back to the example and pick the order where library comes last, the same two rules produce a blue button, because now the library's layer is the later one. This is what makes layers so useful on a real project. Inside each layer, specificity works the way it always has. Between layers, the order we declared at the top of our CSS is the only thing that counts. What About Styles That Aren't in a Layer? Any style that isn't inside an @layer block is called unlayered, and unlayered styles beat every layer. The browser treats them as if they all lived in one final layer that sits above everything we declared. This explains the checkbox in our example. When we load the library outside any layer, its #shop .btn rule becomes unlayered, and it wins over our theme layer even though theme is our highest layer. That's the opposite of what we want, and it leads to the most useful habit for working with layers. Put the code you don't control, like resets, frameworks, and component libraries, into low layers, and keep the code you're actively writing in higher layers or leave it unlayered. The unlayered rule is also why we can adopt layers gradually. Our existing stylesheet keeps working exactly as before, because all of it is unlayered. We can start by wrapping just the library in a layer, and every one of our existing rules will beat it. How Does !important Work With Layers? Here is the part that tends to catch people off guard. For declarations marked !important, the layer order flips. An important declaration in an earlier layer beats an important declaration in a later layer, and important declarations in any layer beat important declarations that are unlayered: @layer reset, theme; @layer reset { [hidden] { display: none !important; } } @layer theme { .card { display: grid !important; } } A .card element with the hidden attribute stays hidden. Both declarations are important, so the earlier reset layer wins. This might seem backwards, but it's intentional. Normal declarations let later layers override earlier ones. !important lets an earlier, more foundational layer say, "This one really can't be overridden," and have that promise hold up against everything that comes after it. In practice, this means !important goes back to being rare and meaningful. We use it in a low layer to protect something essential, like keeping hidden things hidden, rather than in our own code to win a specificity fight. A Few More Layer Tricks There are a few smaller features that come in handy once we start using layers on a real project. Layers Can Be Nested A layer can contain its own layers. That's useful when one big chunk of CSS, like a design system, wants its own internal ordering: @layer library { @layer base, components; } /* Later, we add rules to the nested layer by its full name */ @layer library.components { .btn { padding: 8px 16px; } } From the outside, the whole library layer still sits in one spot in our stack. Inside it, library.base comes before library.components. revert-layer Rolls Back One Layer The revert-layer keyword tells the browser to ignore the current layer's value for a property and use whatever an earlier layer said instead: @layer theme { .btn { background-color: #ffe561; } .btn.plain { background-color: revert-layer; } } Buttons with the plain class skip the theme's yellow and fall back to whatever the library layer gave them. This is a clean way to opt one element out of a theme without having to remember what the original value was. Which Browsers Support Cascade Layers? Cascade layers work in the current versions of Chrome, Edge, Firefox, and Safari, and they have been supported in all of them since early 2022. A browser that doesn't understand @layer ignores the entire block, including the rules inside it, so layered styles don't partially apply in an older browser. They're simply missing. For almost every site today, that's not something to worry about. Conclusion Before cascade layers, the cascade made us express priority through our selectors. If we wanted one rule to win, we made its selector heavier, and that turned every stylesheet into a slow-moving specificity arms race. Layers give priority a home of its own. We declare our layers once, in the order we want them to win, and the selectors inside each layer can go back to being as simple as they need to be. The rules to remember are short. Later layers beat earlier ones. Unlayered styles beat all layers. For !important, that order flips. Pair that with the zero-specificity :where() selector (https://www.kirupa.com/html5/modern_css_selectors.htm), and the days of sprinkling extra IDs into a selector just to win an argument with a library can finally be over. Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Check out some related content: - Modern CSS Selectors: :has(), :is(), :where(), and :focus-visible (https://www.kirupa.com/html5/modern_css_selectors.htm). Style parents with :has() and keep specificity at zero with :where(). - CSS Selectors: Type, Class, and ID (https://www.kirupa.com/html5/css_selectors_type_class_id.htm). Brush up on type, class, and ID selectors and how they rank. - Nesting in CSS (https://www.kirupa.com/html5/css_nesting.htm). Write rules inside rules and keep a component's styles together. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we'll help you out. [Mastery Quiz] Test your knowledge! Take the Reviewing Cascade Layers Quiz: https://www.kirupa.com/quizzes/css_cascade_layers.htm Practice with 4 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]