CSS Video Tutorial: Layers @layer

In this tutorial we will talk about the @layer system in CSS which makes it easier to define the order of precedence of CSS rules. You can group rules into a named layer using the syntax @layer nom-couche {regles}

@layer theme {
  .btn {
    background: red;
  }
}
/* Le bouton sera rouge */

Rules within a layer will always be overridden by rules outside, no matter how specific.

button {
    background: green;
}

@layer theme {
  .btn {
    background: red;
  }
}
/* Le bouton sera vert */

If we have several layers, it’s the last layer that will overload the style, regardless of the level of specificity.

@layer global {
  .btn {
    background: green;
  }
}

@layer theme {
  button {
    background: red;
  }
}
/* Le bouton sera rouge */

The advantage is that layers can be defined upstream to control the order.

@layer global, theme; /* On crée les layers en amont pour définir l'ordre */

@layer theme {
  button {
    background: red;
  }
}

@layer global {
  .btn {
    background: green;
  }
}
/* Le bouton sera rouge, vu que "theme" est la dernière couche de la liste */

The advantage is that a layer can be filled at any time in the style sheet and it is possible to add new rules to it when desired.

On the other hand, if we add a !important on a rule (something that I strongly advise against), the order of priority is reversed and it is the first rule !important encountered in the layers (then globally) who wins.

Use case

We have been working without this layer system for years, so we can wonder about the need for such a feature.

third-party CSS

An interesting use case might be overwriting style from a third-party library. Indeed, if a library has created rules that are too specific, it can be difficult to override them. With the layer system you can import CSS into a specific layer.

@import 'theme.css' layer(utilities);

Thus, by controlling the order of the layers, we can overwrite the rules more easily without having to think about the specificity of the selectors.

Reset & Utility

Another use case concerns the general organization of our CSS if we mix several practices.

  • “Reset” rules should be placed first with the lowest priority to be easily overridden.
  • The “components” or “theme” rules are placed next and allow us to write the style of our elements
  • The “utilities” rules (e.g. “mt-2”, “d-flex”…) are placed last to win no matter what.

It is this type of organization that we find on Tailwind.

LEAVE A REPLY

Please enter your comment!
Please enter your name here