CSS3 & Modern Layouts (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What are CSS Cascade Layers (`@layer`) and how do they resolve specificity wars?
senior LevelCode ExampleSystem Design
In Simple Words:
In large enterprise codebases, developers often resort to !important or chaining classes (.btn.btn.btn) because a third-party CSS library or legacy CSS has higher specificity.
Cascade Layers (@layer) create an explicit precedence hierarchy:
css
/* Establish layer order: Later layers ALWAYS beat earlier layers! */
@layer reset, framework, components, utilities;
@layer reset {
button { padding: 10px; }
}
@layer framework {
/* High specificity inside earlier layer */
#app .btn-primary { padding: 20px; }
}
@layer components {
/* LOW specificity in a later layer WINS over high specificity in an earlier layer! */
button { padding: 8px; } /* WINS! */
}