π What Is @scope?
The @scope rule allows you to limit where certain CSS rules apply by defining a scope root and optional scope boundaries. This makes CSS more modular, predictable, and component-friendly β similar to how scoping works in frameworks like React or Vue. π―
π― Why Use @scope?
- Prevent styles from leaking into other components
- Override styles only within a specific part of the DOM
- Write cleaner, conflict-free CSS
- Create component-level style boundaries
π§© Basic Syntax
Basic @scope Rule
@scope (.card) {
h2 {
color: purple;
}
}β Only <h2> elements inside .card will get the purple color.
β h2 outside .card remains unaffected.
π Scope Root & Boundaries
A scope rule starts at the root selector and stops at theboundaries (optional).
With Boundary Selector
@scope (.profile) to (.profile-footer) {
p {
color: green;
}
}β Styles apply inside .profile
β Styles DO NOT apply inside .profile-footer or deeper
π¨ Real Example
Real-World Scoped Styles
@scope (.card) {
h2 {
font-size: 24px;
}
.btn {
background: blue;
color: white;
}
}HTML
<div class="card">
<h2>Title</h2>
<button class="btn">Click Me</button>
</div>
<h2>Outside Title</h2> <!-- Not affected -->π Only the elements inside .card are styled.
π― Scoping Multiple Roots
Multiple Scope Roots
@scope (.card, .sidebar) {
h3 {
color: teal;
}
}β h3 inside .card or .sidebar will apply
β Others remain untouched
π What @scope Does NOT Do
- It does NOT isolate styles like Shadow DOM
- It does NOT prevent global styles from overriding scoped styles
- It does NOT stop inheritance
Note
βοΈ Cascade + @scope
Conflict Example
h2 {
color: red; /* global */
}
@scope (.box) {
h2 {
color: blue;
}
}β Inside .box: blue
β Outside .box: red
π Using :scope Pseudoclass (Not the Same!)
The :scope pseudo-class refers to the element used in query selection. It is NOT related to the @scope at-rule.
:scope Example
:scope > .item {
background: yellow;
}β¨ Combining @layer + @scope
You can scope styles inside cascade layers for ultra-organized CSS.
Layer + Scope
@layer components {
@scope (.card) {
p {
font-weight: bold;
}
}
}π§ Advanced: Scoped Style Overrides
Chaining Scopes
@scope (.theme-dark) {
@scope (.card) {
h2 {
color: white;
}
}
}β This applies only when BOTH .theme-dark AND .card are parents.
π Best Practices
- Use @scope for component-level CSS π§©
- Use boundaries to prevent style leaking
- Prefer over deeply nested selectors
- Use with @layer for fully structured architecture
- Avoid using @scope everywhere β keep CSS readable