Sub topic 2
Your first @scope rule
This chapter shows how to write a basic @scope rule and what the browser does with it. It assumes you know HTML structure and the DOM tree, CSS selectors and combinators, the cascade (specificity and order of appearance), and the basics of CSS nesting. It does not cover scope limits, :scope in depth, or the specificity and proximity rules. Later chapters take those up.
What @scope does
A normal style rule applies to every element in the document that matches its selector. To keep a rule from reaching too far, you usually prefix every selector with a class, as in .card img and .card a. You repeat the prefix on every rule, and every rule gets more specific as a result.
The @scope at-rule moves that prefix into one place. You name a region of the page once, and every rule inside the block applies only to elements within that region.
Anatomy of the rule
The basic form looks like this:
@scope (.card) {
/* style rules go here */
}| Part | Example | Meaning |
|---|---|---|
| `@scope` | `@scope` | The at-rule keyword. |
| Prelude in parentheses | `(.card)` | A selector list that picks the scope root. |
| Block | `{ ... }` | Ordinary style rules, evaluated relative to the scope root. |
The element matched by the prelude is the scope root. The scope root and everything beneath it in the DOM tree form the scope. A rule inside the block can only match elements in that scope.
The prelude is a real selector, evaluated against the whole document. (.card) finds every element with the class card, wherever it is. Choosing a good root is a topic of its own in the next chapter. For now, use a class selector.
A first example
Here is the markup:
<div class="card">
<img src="photo.jpg" alt="A mountain lake">
<h2>Mountain lake</h2>
<p>Read the <a href="/trip">trip report</a>.</p>
</div>
<p>Back to the <a href="/">home page</a>.</p>
<img src="logo.png" alt="Site logo">Here is the CSS:
@scope (.card) {
:scope {
border: 1px solid #ccc;
padding: 1rem;
}
img {
width: 100%;
}
a {
color: rebeccapurple;
}
}The img rule makes the photo inside the card fill the card's width. The logo outside the card keeps its normal size. The a rule turns the "trip report" link purple. The "home page" link is not inside a .card, so it keeps its normal color.
The :scope rule styles the .card element itself. Writing :scope inside the block is how you reach the root. The next chapters cover it in more detail. All you need for now is that a bare img or a never matches the root, and :scope does.
How the browser reads the rule
Inside @scope, each selector is treated as if it began with :scope and a descendant combinator. So the rules above behave like this:
imgacts like:scope img.aacts like:scope a.
The browser first finds all elements that match the prelude. For each rule, it then checks whether the target element is a descendant of one of those roots.
An element has to pass both tests. The <img> inside .card matches img and has a .card ancestor, so it is styled. The logo matches img but has no .card ancestor, so it is not.
Compared with a descendant selector
You could get the same visual result with ordinary selectors:
.card { border: 1px solid #ccc; padding: 1rem; }
.card img { width: 100%; }
.card a { color: rebeccapurple; }For simple cases like this one, the result is the same. The differences are in how you write and maintain the rules:
- You write the root once, not on every rule. Renaming
.cardto.productmeans editing one line. - Selectors inside the block stay short, so they are easier to read.
- The cascade treats the two forms differently. A rule inside
@scopedoes not get the specificity of the root selector. Later chapters on specificity and proximity explain this. Do not assume the two forms are interchangeable in a stylesheet with competing rules.
Several roots
Many elements on a page can match the prelude. Every match is a scope root, and the block applies inside each of them. A page with five .card elements needs only one @scope (.card) rule.
The prelude also accepts a selector list, so one block can serve several kinds of container:
@scope (.card, .panel) {
a {
text-decoration: underline;
}
}Links inside a .card or inside a .panel are underlined. Links elsewhere are not.
Scopes can also nest in the document. If a .card contains another .card, links in the inner card are in the scope of both roots. The rule applies to them once, as you would expect. Which root counts as the nearest matters when two scopes conflict, and the proximity chapter covers that.
A complete page to try
This page runs as written. Save it as an .html file and open it in a current browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>First @scope rule</title>
<style>
a { color: green; }
@scope (.card) {
:scope {
border: 2px solid #999;
padding: 1rem;
max-width: 20rem;
}
h2 {
margin: 0 0 0.5rem;
font-size: 1.1rem;
}
a {
color: rebeccapurple;
}
}
</style>
</head>
<body>
<div class="card">
<h2>Mountain lake</h2>
<p>Read the <a href="#trip">trip report</a>.</p>
</div>
<p>Back to the <a href="#home">home page</a>.</p>
</body>
</html>Open the page and look at the links. The link inside the card is purple, and the link below it is green. The h2 rule affects only the card's heading.
A global a { color: green; } sits before the @scope block, and the scoped rule still wins inside the card. Two things explain that. The scoped a has the same specificity as the global a, because the (.card) prelude adds nothing to it. It also comes later in the source. Scope proximity can matter as well, but it is only a tiebreaker when specificity is equal, and the proximity chapter explains the full order of checks.
Where the rule can go
You can put @scope at the top level of a stylesheet, as in the examples above. Inside the block you can write ordinary style rules, and you can use nesting syntax. You can also place conditional rules such as @media inside the block, as in any other style context.
Common errors
- Expecting the root to match a type selector.
@scope (.card) { div { ... } }does not style the.cardelement, even if it is adiv. A selector likedivmeans "adivthat is a descendant of the root". To style the root, use:scope. - Writing the root class inside the block.
@scope (.card) { .card a { ... } }looks for a.cardthat is a descendant of a.card. It almost never matches what you meant. Writeainstead. - Reaching outside the scope. Selectors like
body .titleor.sidebar ainside the block are still evaluated relative to the scope. They match only elements inside the scope, so they do not reach elements outside. If a rule must style something outside the root, it belongs outside the@scopeblock. - Assuming
@scopeblocks inheritance. Properties such ascolorandfont-familyinherit down the tree as usual. If.cardis placed inside a dark section, the text still inherits that section's color, unless a scoped rule sets it. The chapter on what@scopedoes not isolate covers this. - Putting an invalid selector in the prelude. A selector the browser cannot parse invalidates the whole
@scoperule, and the browser skips the entire block. Check the prelude first when nothing inside the block applies. - Assuming old browsers ignore it gracefully. A browser that does not know
@scopeskips the whole block, so no scoped rule applies there. The last chapter covers fallback strategies.
Debugging checklist
If a scoped rule does not appear to work, work through these checks in order:
- Does the prelude selector match an element? Try it in the console with
document.querySelectorAll(".card"). - Is the target element a descendant of that match, and not the match itself?
- Does the selector inside the block match the target by itself? Test it with
document.querySelectorAll("img"). - Does another rule win on specificity or order? Browser developer tools show which declarations are overridden.
- Does the browser support
@scope? Check the console and the styles panel for the at-rule being dropped.
Summary of what you can now do
- Write
@scope (selector) { ... }to limit a group of rules to the subtree under matching elements. - Explain that selectors inside the block are relative to the scope root and match descendants only.
- Use
:scopeinside the block to style the root itself. - Describe one practical difference from
.card img: the root is named once, and the cascade handles the rule differently.
Exercise
Given this CSS and HTML, which elements get a red color, and why does the heading not turn red? @scope (.note) { h3 { color: red; } p { color: red; } } <section class="note"> <h3>Title</h3> <p>Body text</p> </section> <h3>Other title</h3> <p>Other text</p>
Show answer
The <h3> and <p> inside the .note section turn red, and the <h3> and <p> after the section stay unchanged, because they are not descendants of a scope root. In this example the heading inside .note does turn red. Only the outside heading does not.
Exercise
You write @scope (.panel) { div { padding: 1rem; } } and your .panel element is itself a div. Does the panel get the padding? How would you change the rule so that the panel and the div elements inside it both get it?
Show answer
No. Inside the block, div means a div that is a descendant of the scope root, so the root itself is not matched. Add a second rule with :scope { padding: 1rem; } inside the same block. Alternatively, write :scope, div { padding: 1rem; }.