CSS layers
What is a CSS layer?
CSS layers are a CSS feature that let you define layers of specificity so that you can have more control over which styles should take priority without worrying too much about specificity or relying on !important hacks.
For example, look at the below code (see here for the Codepen):
<html>
<head>
<style>
@layer theme, utilities;
@layer theme {
div.text {
color: red;
}
}
@layer utilities {
.text-blue {
color: blue;
}
}
</style>
</head>
<body>
<p class="text text-blue">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Neque, aperiam!
</div>
</body>
</html>
Even though the div.text selector has a higher specificity than the .text-blue selector because it targets both a class and an element, the <p>Lorem ipsum...</p> text will be styled blue because .text-blue is defined in the utilities layer which has a higher priority than the theme layer.
In this case, the utilities layer has a higher priority than the theme layer because it’s defined later.
Order of precedence for CSS layers
Here’s the order of precedence for CSS layers – from the highest precedence to the lowest:
- Transition declarations
- Important user agent declarations (browser-specific styling)
- Important user declarations (e.g., via browser settings or browser extensions)
- Important author declarations (styling written by web developers)
- Important @layer 1
- Important @layer 2
- Imporant @layer …
- Important @layerN
- Important unlayered
- Animation declarations
- Normal author declarations (styling written by web developers)
- Unlayered
- @layer N
- @layer. ..
- @layer 2
- @layer 1
- Normal user declarations
- Normal user agent declarations
Note that within author styles, all important declarations within CSS layers take precedence over important declarations outside a layer but normal declarations (without !important) within CSS layers have a lower priority than declarations outside a layer.
Recipes
Define layers without styles
@layer theme, layout, utilities;
Defining the layer names without any styles as above is useful when you want to ensure a specific order of priority. In the above example, styles in the utilities layer will have precedence over the theme and layout layers because it’s defined last.
Create a layer with styles
@layer utilities {
.padding-sm {
padding: 0.5rem;
}
.padding-lg {
padding: 0.8rem;
}
}
Create an anonymous layer
@layer {
p {
margin-block: 1rem;
}
}
Import a stylesheet into a layer
@import "theme.css" layer(utilities);
Nest layers
@layer framework {
@layer layout {
}
}