@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
!importantdeclarations, 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.
!importantreverses the layer order.
- @layer (MDN) (https://developer.mozilla.org/en-US/docs/Web/CSS/@layer)developer.mozilla.org
- Cascade (MDN) (https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade)developer.mozilla.org