Visit homepage

CSS cascade layers

  • Planted:

CSS cascade layers determine the priority of different CSS sources. Specificity rules apply within each layer, but layer order trumps specificity.

Some layers are determined by the source itself, like user agent origin declarations (i.e. browser default styles), which form the lowest priority cascade layer*. You can also define layers explicitly using @layer syntax. MDN has a helpful cascade layer priority ladder.

Usage

If you want to distinguish different sources of author origin declarations (i.e. CSS you write or import), you can create a @layer. I used this today on ide.membrane.io, placing global styles in a layer to deprioritize them under styles from CSS modules.

I’d run into cases where specificity of a declaration in the global stylesheet was higher than that in a CSS module, but I always want the module to win out. Defined layers have lower priority than unlayered styles in the author origin.

globals.css

@layer global {
/* This CSS will be lower priority than CSS modules */
}

*Except when using !important, which moves a declaration to a separate layer.

Reply