CodePark/ questions / Modern CSS
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Modern CSS

What problem do cascade layers (@layer) solve, and how do they interact with specificity?

@layer reset, vendor, components, utilities;

@import url("lib.css") layer(vendor);

@layer components {
  .nav a.active { color: navy; }
}
@layer utilities {
  .text-red { color: red; }
}

Cascade layers give you an explicit priority order for groups of styles, so you stop fighting specificity. Without layers, the only ways to override a style are specificity and source order. That leads to specificity wars, very deep selectors and !important. It is worst with third-party CSS.

@layer lets you declare the order up front. The browser checks layer order before specificity. So any rule in a later layer beats any rule in an earlier one. Specificity is written as (ids, classes, types). In the example, .text-red (0,1,0) beats .nav a.active (0,2,1), because utilities comes later. Specificity only matters inside the same layer.

More rules:

  • Unlayered styles beat all layered styles, for normal declarations.
  • For !important declarations, the order reverses, so earlier layers win.
  • You can put a whole stylesheet into a layer with @import ... layer(name).

All current evergreen browsers support layers. Evergreen browsers update themselves automatically, like Chrome, Firefox, Safari and Edge.

  • Layers give an explicit priority order to groups of styles.
  • Layer order beats specificity.
  • Unlayered styles beat layered ones, for normal declarations.
  • !important reverses the layer order.