@layer & specificity

Control the cascade with layers

Lesson 6 of 20 · 11 min · Module 2: Selectors and the cascade

Specificity battles are a classic CSS headache: a broad rule like nav a beats a component class like .button, and people reach for !important. Cascade layers let you decide the winner by order instead.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Declare and order cascade layers
  • Place rules into layers
  • Resolve conflicts without !important

The idea

Declare the layer order once with @layer reset, base, components;, then wrap rules in @layer base { … }. A rule in a later layer wins over one in an earlier layer, however specific the earlier selector is. Styles outside any layer beat all layered styles.

@layer base, components;

@layer base {
  nav a { color: green; }      /* more specific… */
}
@layer components {
  .button { color: white; }    /* …but this layer wins */
}

01Order beats specificity

Between layers, the browser compares layer order first. Only inside the same layer does specificity decide. That is why .button in components beats nav a in base.

02Unlayered styles win

Rules outside any @layer behave like the last, strongest layer. A common setup imports third-party CSS into a low layer, so your own rules override it without a fight.

@layer vendor, base, components;
@import url("library.css") layer(vendor);

03!important reverses the order

For !important declarations the order flips: an important rule in an early layer beats an important rule in a later one. This protects essential rules in a reset layer, and it is one more reason not to use !important for everyday fixes.

Your turn

At the top of the styles, declare @layer reset, base, components;. Put the * rule in @layer reset, the body and nav a rules in @layer base, and the .button rule in @layer components. The "Start learning" button then shows white text, without changing any selector and without !important.

What the checks look for

  • The button text is white
  • The button background is green
  • Other links stay green
  • .button lives in the components layer
  • nav a lives in the base layer
Try it in the editor →

Take this with you

Layers turn specificity fights into a clear, declared order.

Go a little further

Add a utilities layer after components with a .text-center class, and confirm it overrides rules from every earlier layer.

Learn HTML & CSS Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →