Sub topic 9
Scoping styles: CSS Modules, Shadow DOM and @scope
This chapter assumes you know selectors, specificity and source order, the BEM naming from earlier chapters, and basic npm and bundler use. Here you will learn three ways to stop a rule from matching outside the component it was written for. You will also learn how to choose between them.
The problem scoping solves
Naming conventions such as BEM prevent collisions by discipline. Scoping prevents them by mechanism. Each approach below moves the boundary from "everyone agrees to use .card__title" to "the tool or browser enforces it".
The three approaches enforce the boundary at different points:
| Approach | Enforced by | When | Boundary strength |
|---|---|---|---|
| CSS Modules | Bundler | Build time | Class names only, in your own code |
| Shadow DOM | Browser | Runtime | Strong, in both directions |
| `@scope` | Browser | Runtime | Selector range only, one direction |
CSS Modules
A CSS Modules file is an ordinary stylesheet whose class names are local to the file. The bundler rewrites each class into a unique name and exports a map from the name you wrote to the generated name. Vite, webpack and Next.js support this for files ending in .module.css.
/* Button.module.css */
.root {
padding: 0.5rem 1rem;
}
.primary {
background: var(--color-accent);
}import styles from "./Button.module.css";
export function Button({ primary, children }) {
const className = primary ? `${styles.root} ${styles.primary}` : styles.root;
return <button className={className}>{children}</button>;
}The browser receives something like .Button_root__x7Qa2. Another component can also define .root without a collision, because its generated name differs.
What CSS Modules does not change
- Specificity is unchanged. A hashed class selector is still one class. A module rule still loses to a more specific global rule.
- Source order still decides ties. The order of CSS in the final bundle follows import order, which can differ between pages or after code splitting. Do not rely on one module overriding another. Use
@layerfor that, or compose classes deliberately. - Only classes and IDs are localised. A selector such as
button { margin: 0 }in a module is still global. Many setups run in "pure" mode, which rejects selectors that contain no local class. - Names with hyphens need bracket access.
.card-titleis read asstyles["card-title"]. Many teams write camelCase class names in modules to allowstyles.cardTitle.
Escape hatches
Use :global(...) for a class that must stay unhashed, such as one set by a third-party library:
.root :global(.tooltip-arrow) {
border-color: var(--color-accent);
}Use composes to reuse another local class without repeating declarations:
.danger {
composes: root from "./Button.module.css";
background: crimson;
}Because modules are scoped by a build step, they do not protect against CSS that arrives from outside the bundle. A global stylesheet on the page can still style your elements, since the hashed class sits on ordinary DOM nodes.
Shadow DOM
Shadow DOM gives an element its own subtree with its own style scope. Rules in the page do not match inside the shadow tree, and rules inside do not leak out. This is the strongest isolation CSS offers.
<user-badge>Ada</user-badge>
<script>
class UserBadge extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host { display: inline-block; }
.label {
padding: 0.25rem 0.5rem;
border-radius: 999px;
background: var(--badge-bg, #eee);
}
</style>
<span class="label" part="label"><slot></slot></span>
`;
}
}
customElements.define("user-badge", UserBadge);
</script>Here .label is safe from any page rule named .label, and the reverse is also true. The component defines a few deliberate openings:
- Inherited properties such as
color,font-familyandline-heightpass through the boundary. So do custom properties. This is why--badge-bgworks as a theming hook, and why design tokens from the earlier chapter still apply inside components. :hoststyles the element that owns the shadow root. A page rule such asuser-badge { display: block }can override a:hostrule, because outer-context styles win over:hostin the cascade.::part(label)lets page CSS style elements the component marked with apartattribute:user-badge::part(label) { font-weight: 600 }.::slotted(...)styles light-DOM children that are placed in a slot, but only the top-level slotted elements.
Costs
- A global reset or a base stylesheet does not reach inside. Every component must carry its own resets or take them from inherited values.
- Duplicated
<style>blocks cost memory and parse time. Share one stylesheet across instances withnew CSSStyleSheet()androot.adoptedStyleSheets = [sheet]. - Server rendering needs declarative shadow DOM (
<template shadowrootmode="open">), and tooling support varies. - Theming is limited to custom properties and
part. Consumers cannot restyle internals you did not expose, which is usually the intent.
@scope
@scope is a native CSS at-rule. It limits where a set of rules can match without moving the content into a separate tree. Page styles still reach in, and you do not need a build step.
@scope (.card) to (.card__body) {
:scope {
border: 1px solid #ddd;
}
img {
border-radius: 4px;
}
a {
color: var(--color-accent);
}
}The selector in parentheses is the scope root. The optional to (...) selector is the scope limit. The rules match elements inside the root but not inside a limit element. This produces a "donut": the scope covers the card but stops at its body. That lets you style a wrapper without reaching into nested content, such as a card inside a card's body area.
How @scope affects the cascade
- Bare selectors gain no specificity from the root.
imginside@scope (.card)has the specificity ofimg, which is0,0,1. This differs from nesting, where.card imgwould count both parts. :scopeand&do add weight. Writing:scopecounts as a pseudo-class. Use it only on the root, and be aware that it raises specificity.- Proximity is a new tie-breaker. If two rules have equal specificity and match the same element from different scope roots, the rule whose root is closer in the DOM wins. This step comes after specificity and before source order, so it settles nested themes cleanly.
- Scope only narrows matching. A global
img { ... }can still apply inside the scope.@scopedoes not stop outside rules from getting in.
The proximity rule helps with nested themes:
@scope (.theme-light) {
a { color: navy; }
}
@scope (.theme-dark) {
a { color: lightblue; }
}A link inside .theme-dark nested within .theme-light is styled by the dark rule, because the dark root is nearer. Plain descendant selectors would tie on specificity and let source order decide, which would be wrong for half of the nesting orders.
Check current browser support before using @scope without a fallback. It shipped in Chromium and Safari first and arrived in Firefox later. Rules inside an unsupported @scope block are ignored.
Choosing an approach
These approaches can be combined. A common pairing is CSS Modules for local class names and @layer for ordering across modules. The table below summarises when each fits.
| Situation | Better fit |
|---|---|
| React or Vue app with Vite or webpack | CSS Modules |
| Widget embedded in pages you do not control | Shadow DOM |
| Design-system web components shared across frameworks | Shadow DOM, with custom properties and `part` as the theming API |
| Server-rendered site with no bundler | `@scope` or BEM |
| Styling a wrapper but not nested content | `@scope` with a limit |
| Third-party CSS must still apply | CSS Modules or `@scope`, not Shadow DOM |
Common errors
- Using
styles.card-title. JavaScript reads this as a subtraction. Usestyles["card-title"]or write camelCase names. - Expecting a global stylesheet to affect a shadow tree. It will not, apart from inherited properties and custom properties.
- Relying on
@scopeto block external rules. It only limits where its own rules match. - Putting
:globaleverywhere in modules. This returns you to global CSS with extra syntax. Prefer passing a local class to the child component. - Assuming module CSS order is stable. Code splitting can change it. Layer your overrides.
Exercise
A page has the global rule a { color: red; } and, further down, a stylesheet containing @scope (.nav) { a { color: blue; } }. A link inside .nav is rendered. Which colour does it get, and what would change if the @scope block came first in the file?
Show answer
The link is blue. Both rules have the specificity of one element selector (0,0,1). Bare selectors inside @scope add no weight from the root, so the tie is broken by proximity and source order, and the scoped rule comes later. If the @scope block came first, the global a { color: red; } would be later in the source. The scope only affects proximity when two scoped rules compete, so the global rule would win and the link would be red.
Exercise
A team builds a <user-badge> custom element with Shadow DOM. The page stylesheet sets .label { color: red; }, and the badge contains <span class="label">. Does the label turn red? Name two ways the page author could still change the label's appearance.
Show answer
No. The page rule cannot match elements inside the shadow tree, so the label keeps the colour from the component's own styles or inheritance. The page author can change it through inherited properties or custom properties set on the host, for example user-badge { color: red; --badge-bg: gold; }. If the component exposes part="label", the author can also use user-badge::part(label) { color: red; }.