Sub topic 3
Choosing a scope root
This chapter assumes you can read CSS selectors and combinators, and that you know the basic shape of an @scope rule from the previous chapter. Here you will learn what a scope root is, which selectors make good roots, and how the root decides where your rules apply.
What the scope root is
The scope root is the element, or set of elements, that anchors an @scope rule. You name it in the parentheses after @scope. The browser looks through the whole document for elements matching that selector. Each match becomes a scope root, and the rules inside the block apply only inside it.
@scope (.card) {
img {
width: 100%;
}
a {
color: rebeccapurple;
}
}Here .card is the scope root selector. An img inside a .card gets width: 100%. An img in the header or footer does not.
The selectors inside the block are relative to the root. You do not write .card img. The scope supplies the .card part for you.
<header>
<img src="logo.png" alt="Logo">
</header>
<div class="card">
<img src="a.jpg" alt="">
</div>Only the second image is affected by the rule above.
The root is matched against the whole document
The root selector is not itself limited by any scope. It is matched against the entire document, like an ordinary selector. This has three consequences.
- Any number of elements can be scope roots. If the page has twenty
.cardelements, each is a root, and the rules apply inside all twenty. - A root can sit inside another root. Both scopes apply to elements in the inner one, and the next chapters on specificity and proximity explain how conflicts are resolved.
- The root selector can be anything a normal selector can be: a class, an element type, an attribute selector, a compound selector, or a list.
What kinds of selectors work as roots
Most real code uses one of the following. Each choice has different trade-offs.
| Root selector | Example | Good for | Watch out for |
|---|---|---|---|
| Class | `.card` | Reusable components | Class names can collide with other code |
| Attribute | `[data-component="card"]` | Separating styling hooks from state classes | Longer to type |
| Element type | `article` | Semantic regions | Matches every such element on the page |
| Custom element | `product-tile` | Web components used without Shadow DOM | Needs a unique tag name |
| ID | `#sidebar` | A single, unique region | An ID can match only one element at a time in valid HTML |
| Selector list | `.card, .panel` | Sharing rules across components | Both sets of elements become roots |
Class and attribute roots
A class is the usual choice because components already have one. If you want the root hook to stay stable while classes change for visual state, an attribute is safer:
@scope ([data-component="card"]) {
h2 {
font-size: 1.25rem;
}
}The attribute stays in the markup as long as the component does. Classes like .is-active or .featured come and go.
Element roots
An element selector such as article or nav makes every matching element a root.
@scope (nav) {
a {
text-decoration: none;
}
}This is convenient for site-wide semantic regions. It is risky for a component that happens to use nav, because every nav on the page, including ones from third-party widgets, takes the rule.
Selector lists
You can list several roots, separated by commas. Each matched element is a root, and the same rules apply inside all of them.
@scope (.card, .panel) {
h2 {
margin-block: 0 0.5rem;
}
}This is equivalent to writing the rule once per root. Use it when the components really share the styling. If they only share a few lines, two separate @scope blocks are easier to maintain.
Compound and complex selectors
The root can be more specific than a single class:
@scope (main .card.featured) {
h2 {
color: darkgoldenrod;
}
}Only .card.featured elements inside main are roots. This works, but the root now depends on the page layout. A component whose styling changes when you move it out of main is harder to reuse. Keep the root as simple as the situation allows.
The root itself is not matched by inner selectors
This is the most common surprise. Selectors inside @scope match descendants of the root. They do not match the root.
@scope (.card) {
div {
background: lightyellow;
}
}<div class="card">
<div class="body">This div gets the background.</div>
</div>The outer div.card is a div, but it is the scope root, so it does not receive the background. Only .body does. Writing .card inside the block does not help either, because there is no .card descendant of the root.
To style the root, use the :scope pseudo-class, which the next chapter covers in detail. The short version:
@scope (.card) {
:scope {
border: 1px solid #ccc;
}
}Keep this rule in mind: the root is the starting point, and a plain inner selector means "inside the root".
Descendants of any depth, including nested roots
The scope covers the root's whole subtree, not only its children. A deeply nested img is in scope.
<div class="card">
<section>
<figure>
<img src="deep.jpg" alt="">
</figure>
</section>
</div>@scope (.card) { img { width: 100%; } } styles that image, however many wrappers sit in between. If you want to stop the scope short of some part of the subtree, you need a scope limit. That is a later chapter, and it is the other half of defining a region.
When roots nest, an element inside the inner root is inside both scopes:
<div class="card">
<p>Outer content</p>
<div class="card">
<p>Inner content</p>
</div>
</div>Both p elements are in the scope of at least one .card. The inner p is in the scope of two. For rules that do not conflict, nothing special happens. When two scoped rules conflict, scope proximity decides, which is also covered later.
Choosing a good root
A root should answer one question: where does this component begin? These guidelines help.
- Pick the outermost element of the component. If the card's wrapper is
.card, use it. Rooting at an inner element leaves the wrapper's own styles outside the scope. - Use a hook that exists for the component's lifetime. A class or data attribute that the component always carries is better than a state class.
- Avoid broad roots.
divorsectionmakes nearly every element in the page a root, so the scope no longer limits anything. - Avoid
htmlandbodyas roots. Rules scoped to the whole page are the same as global rules, and you lose the point of scoping. - Prefer a short root selector. Long roots depend on page structure, and they can fail to match when markup is rearranged.
- Do not put the specificity burden on the root. As you will see in a later chapter, the root selector does not add specificity to the rules inside, so
#sidebaris not a stronger root than.sidebar.
Worked example: two components, one stylesheet
Suppose a page has a product card and a promo banner, and both contain links and headings. With global CSS, the rules would clash. With separate scopes, each component states its own rules with short selectors.
<article class="product">
<h2>Desk lamp</h2>
<a href="/lamp">View</a>
</article>
<aside class="promo">
<h2>Free shipping</h2>
<a href="/shipping">Details</a>
</aside>
<h2>Page footer heading</h2>@scope (.product) {
h2 {
font-size: 1.1rem;
}
a {
color: teal;
}
}
@scope (.promo) {
h2 {
font-size: 1.6rem;
text-transform: uppercase;
}
a {
color: crimson;
}
}Each h2 and a takes the rule from the scope it sits in. The footer h2 matches neither root, so no scoped rule touches it. The selectors h2 and a are the same in both blocks, and they do not collide.
Reading the code, you can tell which component owns each rule without reading class prefixes on every selector.
Common errors
- Expecting the root to match inner selectors.
@scope (.card) { .card { ... } }does nothing useful. Use:scope. - Choosing a root that is too general.
@scope (div)scopes almost nothing. - Writing the full path again inside the block.
@scope (.card) { .card img { ... } }looks for a.cardinside the root. That is a different rule fromimg. - Forgetting that roots are document-wide. Two unrelated components that happen to share a class name become roots of the same scope.
- Assuming the root adds specificity. It does not. Do not rely on a root to win conflicts.
Exercise
A page contains <div class="card"><div class="meta">Posted today</div></div> and the stylesheet has @scope (.card) { div { color: gray; } }. Which element turns gray, and how would you also style the outer element?
Show answer
Only div.meta turns gray. The outer div.card is the scope root, and plain inner selectors match descendants of the root, not the root itself. To style the root, add a :scope rule inside the block, for example :scope { color: gray; }.
Exercise
You want one set of heading rules to apply to both .card and .panel components, without affecting headings elsewhere. Write the scope prelude, and say what happens if the page has five .card elements and two .panel elements.
Show answer
Use @scope (.card, .panel) { h2 { ... } }. All seven elements become scope roots, and the h2 rule applies inside each of them. Headings outside those seven subtrees are not affected.