Sub topic 3
Inline @scope in a style element
This chapter assumes you know the DOM tree, CSS selectors, the cascade, specificity, and basic CSS nesting.
Inline `@scope` in a style element
An @scope rule without a prelude uses the parent of its <style> element as the scope root. This is useful when a component owns its styles directly in the HTML.
<section class="promo">
<style>
@scope {
h2 {
color: crimson;
}
:scope {
padding: 1rem;
background: #fff7f0;
}
}
</style>
<h2>Sale ends soon</h2>
</section>
<h2>This heading is unaffected</h2>The h2 rule matches only inside .promo. The :scope pseudo-class refers to the root itself, so it styles the <section>.
Combining `@scope` with CSS nesting
CSS nesting lets a selector contain related selectors. Inside @scope, nested rules remain limited to the scope.
@scope (.card) {
.title {
font-weight: 700;
&:hover {
text-decoration: underline;
}
}
}The & represents .title. The nested rule becomes equivalent to .title:hover, but only within .card.
Choosing among style-isolation tools
| Tool | Main boundary | Build tools required |
|---|---|---|
| `@scope` | A selected DOM subtree | No |
| BEM | Naming convention | No |
| CSS Modules | Generated class names | Usually yes |
| Shadow DOM | Component tree boundary | No, but requires Web Components |
Use @scope when styles need a clear DOM boundary but the markup remains in the document tree. BEM is simple and widely supported, but naming discipline is required. CSS Modules prevent class-name collisions during a build. Shadow DOM provides stronger isolation for reusable components.
What `@scope` does not isolate
@scope limits where selectors match. It does not create a separate document tree.
- Inherited properties can still flow into the scoped region.
- Outside rules can still match elements inside the scope.
- Global styles such as
body { font-family: sans-serif; }still affect descendants. - Custom properties can cross the boundary through inheritance.
Use explicit resets or component tokens when those effects are undesirable.
> callout warning > @scope reduces selector reach. It is not a security boundary or a complete replacement for Shadow DOM.
Browser support and fallback strategy
Check support for the browsers in your target matrix. For older browsers, keep essential layout and readable defaults in ordinary selectors, then use @scope as progressive enhancement. A build step can also transform scoped rules when your toolchain supports that transformation.
Exercise
In an inline style element, what element becomes the root of an @scope rule with no prelude?
Show answer
The parent element of the style element.