Scope and proximity
Definition and purpose
The @scope rule restricts selector matching to a subtree and optionally excludes subtrees at a lower boundary. It is useful for component-local styles without adding a long ancestor chain to every selector.
Scope limit
<!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 (.outer) to (.stop) { p { color: navy; } } </style> </head> <body> <section class="outer"> <div class="inner"> <p id="a">Inside</p> </div> <p id="b">Outer</p> <aside class="stop"> <p id="c">Excluded</p> </aside> </section> <p id="d">Outside</p> </body></html>The limit subtree and outside are unaffected.
Syntax and mental model
Write @scope (.outer) to (.stop) { p { color: navy; } }. The root is included; the limit and its descendants are excluded. The scope prelude does not add specificity to p. Among otherwise equal rules, the nearest scoping root wins, measured in ancestor hops. Explicit :scope in a selector contributes pseudo-class specificity.
Nearer scope wins
<!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 (.inner) { p { color: green; } } @scope (.outer) { p { color: red; } } </style> </head> <body> <section class="outer"> <div class="inner"> <p id="a">Inside</p> </div> <p id="b">Outer</p> <aside class="stop"> <p id="c">Excluded</p> </aside> </section> <p id="d">Outside</p> </body></html>The nearer scope wins even though the outer rule is later.
Common mistakes
Scope does not prevent inherited values crossing a boundary. It restricts selector matching, not the inheritance mechanism. Higher specificity still wins before proximity.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Cascade layers. Next lesson: Native nesting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and proximity — knowledge check
Five questions on scope and proximity.
What does the to() boundary exclude?
Does the scope prelude add selector specificity?
When does proximity decide?
Can inherited color cross a scope limit?
What measures proximity?