CSS cascade layers
Cascade layers in CSS provide a way to have more control over the specificity and order in which styles are applied. To create a layer, use the @layer
rule, enclosing all the styles for that particular layer within its curly braces.
The precedence goes from top-to-bottom where the last defined layer has the highest specificity.
@layer base {
a {
color: blue;
}
}
/* This layer takes precedence over the base layer */
@layer content {
a {
color: red;
}
}
It's also possible to define the order at the top:
@layer base, content;
/* This layer takes precedence over the base layer */
/* Even though it is used before the base layer */
@layer content {
a {
color: red;
}
}
@layer base {
a {
color: blue;
}
}
Styles that are not inside a @layer
rule, will always take precedence over the styles within layers. Regardless of the order.
So when using layers it's probably a good idea to put all the styles inside a layer.
@layer base, content;
@layer base {
a {
color: blue;
}
}
/* The links will be green, */
/* because this takes precedence over the base and content layers. */
a {
color: green;
}
@layer content {
a {
color: red;
}
}
!important
Unfortunately the layers do not take precedence over a style that has been set with !important
.
It's also not possible to override a style with !important
, by using !important
in a layer that has higher specificity.
When using cascading layers, it's really best not to use !important
at all!