HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 1312 min read

CSS Cascade Layers (@layer)

Specificity Only Breaks Ties INSIDE a Layer

Web developmentweb development / CSS architecture

The symptom

You ship a design system. Your rule refuses to apply:

@layer reset, components;

@layer components {

.card .title.is-active { color: red; }   /* specificity 0,3,0 */

}

/* someone's one-off override file, loaded after */

h2 { color: #111; } /* specificity 0,0,1 */

Every active title renders #111. You add a class. Then an id. Then !important. Nothing. DevTools shows your red declaration struck through.

Reasoning it through

Specificity didn't lose the fight — it never entered it. The cascade resolves in this order:

1️⃣ origin + importance

2️⃣ cascade layer

3️⃣ specificity

4️⃣ source order

Step 2 already decided. h2 is unlayered, and unlayered normal styles live in an implicit final layer that outranks every named layer. Specificity is only compared between declarations in the SAME layer. 0,3,0 vs 0,0,1 was never evaluated.

The second trap: !important reverses layer order

So you reach for the hammer:

@layer components { .title { color: red !important } }

…and it still loses to:

@layer reset { h2 { color: #111 !important } }

Because for !important declarations, layer precedence is inverted — the EARLIEST layer wins, and unlayered !important is the weakest of all. Your nuclear option is the first thing to lose. This is the bit people get wrong.

The rule worth memorising

  • One line at the top of your entry CSS is your whole priority system:
@layer reset, vendor, components, utilities;
  • Normal declarations → later layer wins; unlayered beats all layers
  • !important declarations → earlier layer wins; unlayered loses to all layers
  • Inside one layer → ordinary specificity + source order

The fix

Give the override file a layer, declared last:

@layer reset, components, overrides;

@layer overrides { h2 { color: #111 } }

Now a 0,0,1 selector beats a 0,3,0 selector by design instead of by accident — and the !important becomes dead weight you can delete.

Three more things that bite

  • @import "vendor.css" layer(vendor); — park third-party CSS (Tailwind preflight, Bootstrap, a date picker) in an early layer and your app styles stop needing !important entirely.
  • A layer's position is fixed by its FIRST declaration. Re-opening @layer components later appends to it; it does not move it to the end.
  • :where() has specificity 0. Use it in resets (:where(h2) { ... }) so even same-layer rules win easily.

Your exercise

Three files: reset.css, vendor.css, app.css.

Make p { color: blue } in app.css win over .prose p { color: gray } in vendor.css — with no !important, no edits to vendor.css, and ONE new line of code.

Then add !important to the vendor rule. Which colour wins now, and why?