Skip to content
Back to Concepts
CSS UniverseCurriculumCascade Layers (@layer)
Modern CSS ArchitectureCore Concept 05 (Cap of Track 1)

Cascade Layers (@layer)

Tired of CSS specificity wars? @layer lets you define explicit priority tiers for your styles. An ID inside an earlier layer will be defeated by a simple class in a later layer!

1. The Problem @layer Solves

Killing Specificity Wars in Modern Codebases

Imagine you import a third-party UI library. It styled a button with button.btn.btn-primary.large (specificity 0,0,3,1). To change its color in your app, you previously had to write an even uglier selector or use !important.

With @layer: Order Beats Specificity!

By declaring layers, the browser checks which layer came later before it ever looks at selector specificity!

@layer framework, my-app;
/* Framework has 3 classes + 1 ID: */
@layer framework { #nav .btn.primary { color: red; } }
/* Your app has just 1 simple class: */
@layer my-app { .btn { color: blue; } }
/* RESULT: BLUE WINS! Because 'my-app' layer comes after 'framework'! */
2. Live Layer Precedence Simulator

Swap Layer Order & Watch the Winner Change

Notice how the winning background color is completely dictated by the @layer declaration at the top:

Declared Layer Order:
Winning Layer: components (Indigo)
@layer base, components;
@layer base { button { background: #06b6d4; } }
@layer components { button { background: #4f46e5; } }
Winner: components layer is last
3. The Unlayered Styles Rule

Unlayered Styles ALWAYS Win!

What happens to normal CSS written outside of any @layer block?

Styles written outside of any layer are called unlayered styles. In the CSS cascade specification, unlayered styles sit at the very top of the priority ladder! They will seamlessly override any layered style.

/* Inside layer: */
@layer theme { h1 { color: purple; } }

/* Outside layer: */
h1 { color: black; } /* BLACK WINS! Unlayered styles have higher priority. */
Track 1 Complete! Next: Track 2

6. The Box Model & Geometry

Content, padding, border, margin, box-sizing: border-box, and margin collapsing.

Begin Track 2: Box Model