Sub topic 1
Why Global CSS Needs Scoping
Prerequisites
You should know basic HTML structure, the DOM tree, CSS selectors and combinators, and the CSS cascade. You should also understand specificity and basic CSS nesting.
Why global CSS needs scoping
A normal stylesheet is global. A selector such as .card img can match every image inside every element with the card class. As a project grows, names become harder to coordinate. A rule added for one component can affect another component that happens to reuse the same class.
.card img {
width: 100%;
}
.card a {
color: rebeccapurple;
}These rules are limited by the .card selector, but the selector still participates in the document-wide cascade. You must choose unique names, write longer selectors, or rely on conventions such as BEM.
The CSS @scope at-rule limits where its nested rules can match. It creates a local styling region without requiring a build tool or a special naming convention.
Your first `@scope` rule
Write a scope root in parentheses after @scope. The rules inside apply only within matching root elements.
@scope (.card) {
img {
width: 100%;
}
a {
color: rebeccapurple;
}
}Here, .card is the scope root. An image or link must be inside a .card element to match these rules. A matching element outside every .card is unaffected.
<article class="card">
<img src="book.jpg" alt="A book">
<a href="/books">Browse books</a>
</article>
<img src="banner.jpg" alt="Site banner">The image and link in the article are scoped. The banner image is not.
Choosing a scope root
Choose a root that represents the component or region whose styles belong together. A component class is often a useful root:
@scope (.profile-card) {
.name {
font-weight: 700;
}
.avatar {
border-radius: 50%;
}
}The root can also be an element, attribute selector, or more specific selector:
@scope dialog[open] {
button {
cursor: pointer;
}
}If several elements match the root selector, each matching element creates its own scope. Keep the root stable and meaningful. Avoid using a temporary styling class that may disappear when the component changes.
Exercise
Why does the banner image in the earlier example remain unaffected?
Show answer
It is not inside an element matching the .card scope root.