Sub topic 2
Why Layer Order Beats Specificity
Assume you know CSS selectors, specificity, source order, and how to inspect styles in browser DevTools. Cascade layers add another decision step before specificity.
Layer Order Comes First
The cascade compares declarations in stages. For normal declarations, the browser first compares origin and importance, then cascade layer order. It compares specificity only when competing declarations are in the same layer.
A later layer wins over an earlier layer, even when the earlier selector is more specific:
@layer base, utilities;
@layer base {
#nav a.link {
color: blue;
}
}
@layer utilities {
.red {
color: red;
}
}An element matching #nav a.link.red gets a red color. The selector in base has greater specificity, but utilities comes later.
Unlayered Styles Win
Normal declarations outside any layer have priority over normal declarations inside named layers. This remains true regardless of specificity:
@layer components {
button {
background: gray;
}
}
button {
background: green;
}The unlayered button rule wins. Treat unlayered CSS as an implicit final layer for normal declarations.
A Practical Layer Structure
A project can set its policy once and then place rules in separate files:
@layer reset, base, components, utilities;
@layer reset {
* {
box-sizing: border-box;
}
}
@layer base {
body {
color: #222;
}
}
@layer components {
.card {
padding: 1rem;
}
}
@layer utilities {
.text-red {
color: red;
}
}This structure gives utilities a predictable way to override component styles without writing highly specific selectors. Keep application rules inside layers if you want this ordering to control the whole project.
Importing CSS into a Layer
Place third-party CSS in an early layer. Your later layers can then override it without specificity battles:
@layer vendor, site;
@import url("vendor.css") layer(vendor);
@layer site {
.btn {
padding: 0.5rem 1rem;
}
}The @import rule must appear before ordinary style rules. The imported stylesheet becomes part of vendor, so site wins for normal conflicts.
Exercise
Which color applies to a link matching #nav a.link.red when base contains #nav a.link { color: blue; } and the later utilities layer contains .red { color: red; }?
Show answer
Red. Layer order is checked before selector specificity, and utilities is later.