Sub topic 14
Cascade layers with @layer
This chapter assumes you can calculate a selector's specificity as an (ID, class, type) triple. It also assumes you know that source order breaks ties and what !important does.
Why layers exist
Specificity fights usually start when a reset or third-party stylesheet uses strong selectors, such as #nav a. Your own rule a then loses, even if it comes later. A cascade layer lets you decide which group of rules wins, before specificity is compared.
Declaring layers
@layer creates a named layer. The first statement below sets the order for all layers. Later layers beat earlier ones.
@layer reset, components;
@layer reset {
#nav a { color: black; } /* (1,0,1) */
}
@layer components {
a { color: blue; } /* (0,0,1) */
}Links in #nav are blue. The browser compares layers first, and components comes after reset. The #nav a rule is more specific, but specificity is only compared between rules in the same layer.
Where layers sit in the cascade
For normal declarations, the browser checks these in order and stops at the first difference:
- Origin and importance.
- Layer order, where a later layer wins.
- Specificity.
- Source order.
Styles outside any layer are treated as a final implicit layer. They beat every named layer, whatever their specificity.
Importance reverses the order
With !important, the layer order flips. An important declaration in an earlier layer beats one in a later layer. Important layered declarations also beat important unlayered ones.
@layer base, theme;
@layer base { p { color: red !important; } }
@layer theme { p { color: blue !important; } }The paragraph is red. The reset layer is the safest place for rules you never want overridden.
Practical patterns
- Put third-party CSS in an early layer with
@import url("lib.css") layer(vendor);. Your own unlayered CSS then overrides it with simple selectors. - Declare the order once at the top of your main stylesheet. Without that statement, layers are ordered by first appearance.
- Reopening a layer with the same name adds rules to it. It does not create a new layer.
@layer vendor, base, components, utilities;A common order runs from least to most specific in intent: vendor, base, components, utilities.
Checking layers in developer tools
Modern browsers show the layer name beside each rule in the Styles pane. If a rule you expected to win is crossed out, check its layer before you compare selectors.
Exercise
Given @layer a, b; with @layer a { #x { color: red; } } and @layer b { p { color: green; } }, what color is <p id="x">? What changes if both declarations get !important?
Show answer
Green, because layer b comes later and layers are compared before specificity. With !important on both, the order reverses, so layer a wins and the text is red.