A new cascade origin above specificity

CSS is getting @layer, a feature that landed in experimental browsers shortly after being championed by Miriam Suzanne. Bramus Van Damme has published a detailed write-up of the mechanics:

With Cascade Layers coming, we developers will have more tools available to control the Cascade. The true power of Cascade Layers comes from its unique position in the Cascade: before Selector Specificity and Order Of Appearance. Because of that we don't need to worry about the Selector Specificity of the CSS that is used in other Layers, nor about the order in which we load CSS into these Layers — something that will come in very handy for larger teams or when loading in third-party CSS.

Bramus Van Damme

The important consequence: layers decide which selectors win, which means retraining how we reason about applied styles. A higher layer can beat a traditionally stronger selector even when the selector inside it is weaker.

Because the conflicting CSS at the bottom sits outside any layer, it wins despite the weaker selector. There is also no limit of one: you define and order as many layers as you need.

@layer reset;     /* Create 1st layer named “reset” */
@layer base;      /* Create 2nd layer named “base” */
@layer theme;     /* Create 3rd layer named “theme” */
@layer utilities; /* Create 4th layer named “utilities” */
/* Or, @layer reset, base, theme, utilities; */

@layer reset { /* Append to layer named “reset” */
  /* ... */
}

@layer theme { /* Append to layer named “theme” */
  /* ... */
}

@layer base { /* Append to layer named “base” */
  /* ... */
}

@layer theme { /* Append to layer named “theme” */
  /* ... */
}

An emerging authoring pattern

A likely convention is to layer everything so priority levels stay explicit, reserving unlayered CSS only for extreme overrides — or better, expressing those as a top-level layer as well:

  1. Everything lives in a layer.
  2. Resets occupy the lowest layer.
  3. Third-party CSS sits in the middle layer or layers.
  4. Team-authored CSS goes in the highest layer.

Unlike z-index, no gaps need to be left between priorities, since layers can be reordered later without attaching numbers.

Debugging and the unlayered reversal

DevTools will need to surface layer placement clearly; weaker-looking selectors winning on layer position alone is likely to confuse people for some time.

The feature is volatile. On October 6th, 2021, a CSSWG resolution decided that unlayered styles are actually the strongest styles, not the weakest — the reverse of the earlier assumption.

Support

Browser support data from Caniuse; a number indicates support at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
9997No9915.4

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
15716015715.4