Sub topic 1
Why global CSS needs scoping
CSS rules apply to the whole document. A selector you write for one component can match elements in other components, and other people's selectors can match yours. This chapter explains why that happens, the problems it causes, and what a scoping mechanism has to do to fix them. The rest of the tutorial then introduces the CSS @scope at-rule as that mechanism.
Prerequisites
This chapter assumes you already know the following:
- Basic HTML structure and the DOM tree: parents, children, descendants, siblings.
- CSS selectors and combinators, such as
.card a,.a > .band.a + .b. - The cascade. When rules conflict, the browser compares origin and importance, then specificity, then order of appearance.
- The basics of CSS nesting, where a rule contains other rules and
&refers to the parent selector.
You do not need to know @scope yet. You also do not need to know BEM, CSS Modules or Shadow DOM. They appear briefly here and get their own comparison later in the tutorial.
The working model: one namespace, one cascade
A stylesheet is not attached to a component. The browser collects every stylesheet that applies to a document and treats the rules as one list. For each element, it finds every rule whose selector matches and resolves conflicts with the cascade. Three facts follow from that:
- Class names, IDs and element names share one namespace. A
.titleselector matches every element withclass="title", wherever it appears. - Matching depends only on the selector and the element's position in the DOM. The selector does not know which file it was written in or which component it was written for.
- Declarations from different rules merge. If two rules match the same element and set different properties, the element gets both sets. Only conflicting properties are decided by the cascade.
This model suits styling a single page, where the author controls everything. It breaks down when many authors, files and components contribute to the same page.
Failure mode 1: name collisions
Two authors choose the same obvious class name for different purposes.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Global collision</title>
<style>
/* Written for the product card */
.title {
font-size: 1.5rem;
color: navy;
}
/* Written months later for the settings panel */
.title {
font-size: 0.75rem;
text-transform: uppercase;
}
</style>
</head>
<body>
<article class="card">
<h2 class="title">Product name</h2>
</article>
<section class="panel">
<h3 class="title">Settings</h3>
</section>
</body>
</html>Open this page and both headings are navy, small and uppercase. The two rules have equal specificity, so the later font-size wins. The color and text-transform declarations do not conflict with anything, so they merge. The card title shrinks and turns uppercase, and the settings title turns navy. Neither author wrote a bug in their own rule. The bug exists only in the combination.
Collisions are hardest to spot when the two rules live in separate files. A page can look correct until the order of two <link> elements changes.
Failure mode 2: selectors that reach too far
Descendant selectors are written with a component in mind, but they match anything below the ancestor.
.card a {
color: rebeccapurple;
text-decoration: none;
}This rule is meant to style the links in a card's text. It also matches:
- links inside a comment widget someone embeds in the card later,
- links in a nested card,
- links in a third-party share menu rendered inside the card.
Each of those has its own link styling, and now each is overridden by a rule it knows nothing about. The descendant combinator has no stopping point. It matches at any depth.
Here is the markup in which the problem appears.
<div class="card">
<p>Read the <a href="/guide">guide</a>.</p>
<div class="share-menu">
<a href="/share/mail">Mail</a>
<a href="/share/chat">Chat</a>
</div>
</div>The share menu's links turn purple with no underline, even though the menu was designed to show them as white buttons. The card author did not intend this. The selector made it happen.
Failure mode 3: specificity escalation
You can respond to a leaking or conflicting rule by making your own selector more specific. Specificity is a weight, so a heavier selector wins. This works, but each fix raises the bar for the next one.
.card .title { color: navy; }
.sidebar .card .title { color: gray; }
#page .sidebar .card .title { color: black; }The third rule wins everywhere in the page. To override it, a later rule needs an ID, another class, or !important. Over time the codebase accumulates:
- long selectors that mirror the DOM structure and break when the markup changes,
- IDs used for styling, which no class selector can override,
!importantdeclarations, which can only be beaten by other!importantdeclarations.
The underlying cause is that selectors have to do two jobs. They pick the right elements and they limit the reach of the rule. Specificity is a poor tool for the second job.
Failure mode 4: order dependence
When two rules have equal specificity, the one that appears later wins. In a global cascade, "later" depends on how the page loads stylesheets:
- the order of
<link>and<style>elements, - bundler output order, which can change when imports change,
- lazy-loaded stylesheets that arrive after the first render.
A component that looks right in isolation can look wrong when another stylesheet loads after it. A refactor that moves an import can change the rendering without touching any CSS.
Failure mode 5: deletion is risky
Because any rule might match any element, you can't tell who depends on a rule. Deleting .title styles means searching every template for that class, including templates in other repositories that share the stylesheet. Teams often leave old rules in place, and the stylesheet only grows.
What scoping has to provide
A useful scoping mechanism addresses these failures by adding a boundary to a rule. Compare these requirements with the failure modes above:
| Requirement | Failure it addresses |
|---|---|
| A rule can name the region of the DOM it applies to | Name collisions, selectors that reach too far |
| Selectors inside the region stay short, so no structural chains are needed | Specificity escalation |
| The region can have an inner boundary that stops the rule | Leaking into embedded widgets |
| Region membership influences which rule wins, not only source order | Order dependence |
| Removing a region's rules affects only that region | Risky deletion |
The @scope at-rule supplies these pieces. A first look at the syntax shows the idea. The next chapter covers it properly.
@scope (.card) {
.title {
color: navy;
}
}The .title rule applies only to .title elements inside a .card. A .title in the settings panel is untouched, and the card's rule needs no long selector to achieve that.
Existing workarounds and their costs
Developers have worked around global CSS for years. These approaches are compared with @scope in a later chapter. Here is a short summary of what each one costs.
- Naming conventions such as BEM. You write long, unique class names like
card__title--large. This works with plain CSS, but it depends on every author following the convention. It also makes markup verbose, and a naming mistake silently reintroduces a collision. - Build-time tools such as CSS Modules. The build rewrites class names to unique ones. This prevents collisions, but it needs a bundler and doesn't help with CSS delivered outside it, such as third-party stylesheets and CMS content.
- Shadow DOM. The browser enforces a hard boundary around a component's styles. This is strong isolation, but it requires custom elements or declarative shadow roots, and it blocks outside styling unless you design hooks for it.
Each approach trades something away: discipline, tooling or flexibility. @scope aims for a native, selector-level boundary that needs no renaming and no build step. It is also weaker than Shadow DOM, which a later chapter covers.
Common errors when diagnosing global CSS problems
These mistakes come up repeatedly when people debug conflicts:
- Assuming a rule replaces another. Rules merge declaration by declaration. If an element looks wrong, check each property separately in the browser's DevTools "Styles" pane. Overridden declarations are shown struck through.
- Fixing a symptom with more specificity. If you add an ID or
!importantto beat a rule, you have probably made the next conflict harder to fix. Ask first why the other rule matched at all. - Blaming load order alone. Order only matters when specificity is equal. If your rule loses despite coming later, compare specificity before reordering files.
- Treating descendant selectors as "inside this component only". The combinator has no depth limit and no awareness of components.
- Confusing inheritance with matching. Some properties, such as
colorandfont-family, pass from parent to child without any rule matching the child. Scoping a selector does not stop inheritance. Later chapters return to this limit.
Summary of the working model
- Selectors match by element and position in the DOM, not by the component they were written for.
- All matched rules merge into one result for each element, with the cascade deciding only conflicting properties.
- Without a boundary, the usual fixes (longer selectors, IDs,
!important, fixed file order) make the code harder to change. - A scoping mechanism puts the boundary into the rule itself. This is the job of
@scope, which the next chapter introduces.
Exercise
A page has .title { color: navy; font-size: 1.5rem; } in card.css and .title { font-size: 0.75rem; } in settings.css, loaded in that order. Both stylesheets are global and both rules have the same specificity. What color and font size does an element with class title get, and why?
Show answer
The color is navy and the font size is 0.75rem. The rules merge. The color declaration doesn't conflict with anything, so it applies. The font-size declarations conflict, specificity is equal, and the later rule (from settings.css) wins.
Exercise
The rule .card a { color: rebeccapurple; } is meant for links in a card's text. Name one way it can restyle links you didn't intend, and explain why the selector allows that.
Show answer
It also matches links inside anything nested within the card, such as an embedded share menu or a nested card. The descendant combinator matches at any depth and has no way to stop at a component boundary.
Exercise
A teammate fixes a color conflict by changing .card .title to #page .sidebar .card .title. Give two problems this creates for future changes.
Show answer
Any later override needs equal or higher specificity, such as another ID or !important, so conflicts get harder to resolve. The long selector also copies the DOM structure, so it breaks when the markup is rearranged.