CSS @scope At-Rule
The @scope at-rule limits selectors to a chosen portion of the document, optionally stopping at a defined boundary. It helps avoid unintended styles outside a component.
@scope Syntax
@scope (.card) {
h2 {
color: #0056b3;
}
}
A scoped selector matches elements within its scope root. An optional to boundary excludes matching subtrees, making it possible to style one component without affecting nested components.
How @scope Works
The scope root does not add specificity to selectors inside the rule. If competing declarations otherwise tie in origin, importance, layer, and specificity, the cascade can prefer the selector with fewer hops to its scope root.
The @scope at-rule limits selectors to a chosen portion of the document, optionally stopping at a defined boundary. It helps avoid unintended styles outside a component.
The @scope rule limits the reach of enclosed selectors to a scoping root, optionally ending at a lower boundary. It is especially useful when styling components that contain nested components of the same kind.
Scope Roots
The selector in parentheses identifies the scoping root. Rules inside the block apply to matching descendants within that scope.
The syntax @scope (.card) to (.nested-card) prevents matching into nested-card subtrees. Without an explicit root, @scope can use the enclosing element as an implicit scope root in an embedded style context.
Lower Boundaries
Use @scope (.card) to (.nested-card) to prevent selectors from matching content within a nested component.
Proximity in the Cascade
When otherwise tied declarations compete, scoping proximity can affect which declaration wins. Normal cascade origin, importance, layers, and specificity still matter.
@scope Example
Check current browser support before using this feature in production, and keep a usable fallback where support is unavailable.
HTML
<div class="card"><h2>Scoped heading</h2><p>Only this card heading is blue.</p></div>
<h2>Outside heading</h2>
CSS
@scope (.card) {
h2 {
color: #0056b3;
}
}
Browser Support
Support varies by feature and browser version. For current compatibility, consult Can I Use? and search for the relevant feature.
Scope proximity can break ties late in the cascade, after origin, importance, layer, and specificity. It does not automatically make every scoped rule more specific.
Specifications
This feature is described in CSS Cascading and Inheritance Level 6.
