develop
Layers
CSS layer to tame specificity.
CSS recently introduced a new feature called layers
to the cascade specification.
This important feature allows more granularity and control over CSS specificity and overrides, especially when discussing shared libraries and design systems.
Layers allow authors and Wanda consumers to define specificity layers independently from when a specific style appears on the page and the parsing order.
Here is a quick example, in the code belove, if we remove the @layer reset
declaration the p
element would be blue
.
Still, since the browser parses the CSS placed outside any layer (implicit final layer) after all the styles coming from layers, the p
element is red
even if p[data-blue]
has higher specificity.
p {
/* specificity of 0,0,1 - implicit (final) layer */
color: red;
}
@layer reset {
p[data-blue] {
/* specificity of 0,1,1 - explicit "reset" layer */
color: blue;
}
}
Wanda layers
Wanda defines 4 CSS layers, referenced internally inside the packages that compose the design system:
@layer core, utilities, components, overrides;
Let's see a real example. The Button
component declares its styles inside the components
layer:
@layer components {
.Button {⋯}
}
Now, the Snackbar
needs to override some properties of the button, but we cannot use !import
. Layers rescue us by allowing us to section the cascade in different layers of specificity. Now let's see what the Snackbar
can do to solve this issue.
@layer overrides {
.Action {
color: var(--snackbar-bg);
background-color: var(--snackbar-fg);
&:is(:active, :hover) {
color: var(--snackbar-bg);
background-color: var(--snackbar-fg);
opacity: 80%;
}
}
}
Since we declared the overrides
scope after components, it has higher precedence in the cascade and specificity computing. This way, the styles declared inside a layer overrides
will win over the ones declared inside the layer components
.
Advantages for consumers
When consumers need to write down their styles and overwrite some properties, any CSS defined by the consumer in their projects will always win over the styles coming from the design system unless the user declares them inside a new and local CSS layer.