Layered stylesheets and component isolation
Definition and purpose
Layers govern declaration precedence; scope limits selector matching to a region. Combine these with inherited tokens to express a component contract without unnecessarily increasing specificity.
Order component layers
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } @layer base, components; @layer base { #a { color: red; } } @layer components { .label { color: blue; } } </style> </head> <body> <section class="panel"> <p class="label" id="a">Inside</p> <section class="nested"> <p class="label" id="b">Nested</p> </section> </section> <p class="label" id="outside">Outside</p> </body></html>The later normal layer wins despite lower specificity.
Syntax and mental model
Declare @layer reset, components, overrides before defining the layers. For normal author declarations, later layers win over earlier layers regardless of selector specificity; unlayered normal rules outrank layered ones. Important declarations reverse the layer order. @scope (.panel) to (.nested) can exclude a nested subtree from matching. Inheritance can still cross that boundary, so set explicit token defaults where appropriate. If scope support is absent, retain a simple baseline selector.
Exclude a nested subtree
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } @scope (.panel) to (.nested) { .label { color: green; } } </style> </head> <body> <section class="panel"> <p class="label" id="a">Inside</p> <section class="nested"> <p class="label" id="b">Nested</p> </section> </section> <p class="label" id="outside">Outside</p> </body></html>Only the matching label within the scope and above its lower boundary changes.
Common mistakes
A scope boundary is not Shadow DOM and does not block inheritance. A layer is not a selector boundary; any matching rule can still affect an element.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Naming and component boundaries. Next lesson: Design system and theme project.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Layered stylesheets and component isolation — knowledge check
Five questions on layered stylesheets and component isolation.
Which normal author layer wins when later layers conflict?
How does important change layer order?
What does the to clause of @scope define?
Does scope prevent inheritance?
Does a layer itself restrict selectors to components?