Sub topic 9
Scoping styles: CSS Modules, Shadow DOM and @scope
This chapter assumes you know CSS selectors, the cascade and specificity, and how BEM names keep selectors flat. It also assumes you can run npm scripts.
The problem scoping solves
CSS rules are global. A .title rule in one file affects every .title on the page. BEM avoids collisions through discipline: you name things card__title and trust everyone to follow the rule. Scoping moves that guarantee from people into tooling or the browser.
There are three common approaches. They differ in where the boundary is enforced.
| Approach | Boundary enforced by | Needs a build step | Styles leak in from outside |
|---|---|---|---|
| CSS Modules | Bundler renames classes | Yes | Yes, through global selectors |
| Shadow DOM | Browser | No | No, except inherited properties and custom properties |
| `@scope` | Browser selector matching | No | Yes, it limits reach but does not isolate |
CSS Modules
A CSS Modules file is an ordinary stylesheet whose class names are local to that file. The bundler rewrites each class to a unique name, such as Button_root__x7Qa2, and gives your code a map from the original name to the generated one.
/* Button.module.css */
.root {
padding: 0.5rem 1rem;
}
.primary {
background: var(--color-accent);
}import styles from "./Button.module.css";
export function Button({ label }) {
return `<button class="${styles.root} ${styles.primary}">${label}</button>`;
}Two components can both define .root without a collision. Specificity stays low because each rule is still a single class selector.
Common errors:
- Styling an element with a tag selector alone, such as
h2 { ... }. Tag selectors are not renamed, so they remain global. Pair them with a local class. - Using hyphenated names such as
.primary-button. In JavaScript you must writestyles["primary-button"]. Camel case avoids this. - Expecting isolation from other stylesheets. A global rule can still override a module rule.
Shadow DOM
Shadow DOM gives an element a separate tree with its own style scope. Styles outside do not match inside, and styles inside do not leak out.
<user-badge></user-badge>
<script>
class UserBadge extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
.name { color: var(--badge-color, #333); font-weight: 600; }
</style>
<span class="name">Ada</span>
`;
}
}
customElements.define("user-badge", UserBadge);
</script>Inherited properties such as color and font-family still pass through the boundary, and so do custom properties. The example uses --badge-color as the public styling hook. A page can set user-badge { --badge-color: crimson; } and the component picks it up.
The trade-off is rigidity. Global resets, utility classes and design-token stylesheets do not reach inside, so each component must receive what it needs through custom properties or its own copy of the styles.
@scope
The @scope at-rule limits a rule's reach to a subtree of the page. It needs no build step and creates no separate tree.
@scope (.card) to (.card__footer) {
:scope {
border: 1px solid #ddd;
}
p {
margin-block: 0.5rem;
}
}The part in the first parentheses is the scope root. The optional to (...) part is the scope limit. Here the p rule applies to paragraphs inside .card but stops at .card__footer, which gives a "donut" shape. :scope refers to the root itself.
@scope also changes the cascade. When two rules match, the one whose scope root is closer to the element wins, before specificity is compared. This helps with nested components of the same kind. Check browser support for your audience before depending on it, and keep a fallback for older browsers.
Choosing an approach
Use Shadow DOM for widgets embedded in pages you do not control. Use CSS Modules when a component framework and bundler are already in place. Use BEM, optionally with @scope, for server-rendered or static sites.
These techniques combine well with earlier chapters. Tokens defined on :root pass through a shadow boundary, and @layer ordering still decides conflicts between module styles and utilities.
Exercise
A CSS Modules file contains h2 { margin: 0; }. Why does this rule still affect every h2 on the page, and how would you fix it?
Show answer
The bundler renames only class (and ID) selectors. A tag selector is left as written, so it stays global. Add a local class, for example .title { margin: 0; }, and apply it with styles.title.
Exercise
A page sets user-badge .name { color: red; }. Does this change the .name span inside the shadow root of the component above? What is the supported way to let the page change the colour?
Show answer
No. Selectors in the outer document do not match elements inside a shadow tree. The page should set the custom property the component exposes, such as user-badge { --badge-color: red; }.