Sub topic 2
Styling the Root with `:scope`
Assume you know the DOM tree, CSS selectors, combinators, specificity, the cascade, and basic CSS nesting. This chapter focuses on four related parts of @scope: styling its root, excluding a subtree, calculating specificity, and resolving scoped conflicts.
Styling the root with `:scope`
The selector in @scope (...) identifies the scope root. Rules inside the block apply to matching descendants, but the root itself is not selected by an ordinary descendant selector. Use :scope to select the root element.
<!doctype html>
<html>
<head>
<style>
@scope (.card) {
:scope {
border: 1px solid #ccc;
padding: 1rem;
}
img {
width: 100%;
}
a {
color: rebeccapurple;
}
}
</style>
</head>
<body>
<article class="card">
<img src="cover.jpg" alt="A mountain landscape">
<a href="/details">Read details</a>
</article>
</body>
</html>Here, :scope means “the current .card root.” The img and a selectors match elements inside that root.
Scope limits and donut scopes
A scope limit stops matching at a selected descendant. This creates a donut scope: the styles apply inside the root but outside the excluded subtree.
@scope (.card) to (.card-content) {
img {
border-radius: 50%;
}
}An image directly inside .card matches. An image inside .card-content does not, because matching cannot cross that boundary.
Specificity inside `@scope`
The scope root does not add specificity to selectors inside the block. In this example, a has the specificity of one type selector:
#sidebar a { color: blue; }
@scope (#sidebar) {
a { color: green; }
}
.link { color: red; }The .link rule wins because its class selector has greater specificity. The scope root #sidebar is not counted as though it were written before a.
Scope proximity resolves ties
When scoped rules have equal specificity, the browser compares scope proximity before source order. The rule whose scope root is reached in fewer ancestor hops wins.
@scope (.dark) {
a { color: plum; }
}
@scope (.light) {
a { color: darkmagenta; }
}For an a inside .dark nested within .light, the .dark rule wins because .dark is closer.
Exercise
In @scope (.panel) to (.footer), does a link inside .footer receive the scoped link styles?
Show answer
No. The scope limit stops matching at .footer, so its descendants are excluded.