Chapter 2 · Practice 2 of 4
Use cascade layers to order groups of styles explicitly
Why it matters
Cascade layers let you put styles into named groups and decide which group wins, before specificity is even compared. A one class rule in a later layer beats a rule with an ID in an earlier layer.
Declare the order once, at the top of your main stylesheet. MDN notes that layers take precedence in the order they are first created, so this statement fixes the order no matter where each layer's rules appear later.
A common structure:
reset: browser normalizationbase: element defaults such as headings and linkscomponents: buttons, cards, formsutilities: small single purpose classes that should always win
Third party CSS can be imported straight into a low priority layer, so your own styles override it without higher specificity.
Do
- Declare the full layer order in one statement at the top of the entry stylesheet
Example
@layer reset, base, vendor, components, utilities;
@import url("datepicker.css") layer(vendor);
@layer components {
.button { background: var(--color-accent); }
}
@layer utilities {
.hidden { display: none; }
}