Sub topic 10
@scope versus BEM, CSS Modules and Shadow DOM
This chapter assumes you know the cascade and specificity, can write CSS selectors and combinators, and have written a basic @scope rule with a root and a limit. It compares @scope with three other ways to keep component styles from colliding: the BEM naming convention, CSS Modules, and Shadow DOM. The goal is to help you pick one, or combine them, for a real project.
What each approach actually does
All four approaches answer the same question: how do I stop .title in one component from styling .title in another? They answer it at different layers.
| Approach | Layer | Where the boundary is enforced | Needs a build step or JavaScript |
|---|---|---|---|
| BEM | Naming convention | Nowhere. Developers agree to use unique names. | No |
| CSS Modules | Build tooling | Class names are rewritten to unique strings at build time. | Yes, a bundler or compiler |
| `@scope` | Selector matching in CSS | An element matches only if it lies inside the scope root and outside the scope limit. | No |
| Shadow DOM | DOM tree | Separate tree. Outside selectors cannot reach inside. | Yes, JavaScript or declarative shadow DOM |
Keep this in mind throughout the chapter: only Shadow DOM is a hard boundary. The other three reduce collisions without making them impossible.
BEM: scoping by naming
BEM (Block, Element, Modifier) makes every class name globally unique by convention. A block is card, an element is card__title, and a modifier is card--featured.
.card { border: 1px solid #ccc; padding: 1rem; }
.card__image { width: 100%; }
.card__title { font-weight: 700; }
.card__title--active { text-decoration: underline; }BEM has real strengths:
- Every selector has the same specificity, one class, so the cascade is predictable.
- It works in any browser, with any tooling, in any language that emits HTML.
- Names are greppable. Searching for
card__titlefinds every use.
It also has costs:
- The markup carries long class names, and every element needs a class.
- Nothing enforces the convention. One developer writing
.titleglobally breaks the guarantee. - Third-party content, such as rendered Markdown or a CMS body, has no BEM classes, so you cannot style it by class at all.
@scope removes the need for the prefixes. The scope root plays the role of the block name:
@scope (.card) {
img { width: 100%; }
.title { font-weight: 700; }
.title.active { text-decoration: underline; }
}The selectors are short, and the markup can use plain element selectors for content you do not control. The price is that the .title rule is still a global name. Another stylesheet can match .title outside .card without any conflict, and that is fine. But @scope does not stop outside rules from reaching in, as the section on limits of isolation explains.
CSS Modules: scoping by rewriting
CSS Modules is a build-time feature of bundlers such as webpack and Vite. You write ordinary class names, import the stylesheet as an object, and the tool replaces each class with a unique generated name.
/* card.module.css */
.title { font-weight: 700; }
.image { width: 100%; }import styles from "./card.module.css";
const title = document.createElement("h2");
title.className = styles.title; // for example "card_title__x7Qa2"The output class might be card_title__x7Qa2. Two components can both define .title, and the generated names never clash. The guarantee is strong for class names, and it holds across the whole bundle.
The trade-offs are different from BEM's:
- You depend on a toolchain and on a JavaScript import for every class. Static HTML, server-rendered templates in other languages, and CMS content do not fit easily.
- The scoping is a property of the build output, not of the browser. In DevTools you see hashed names, which makes debugging and external overrides harder.
- Element selectors such as
aorimgare not rewritten. A module rule like.card a { ... }is only scoped by its class part. - Styling a child component's internals from a parent needs
:globalor extra props.
@scope can be used inside a CSS Module file, but the two features overlap. Many teams in a CSS Modules codebase gain little from adding @scope. The case where it helps is the donut: a module-scoped rule that should stop at a nested component's boundary.
Shadow DOM: scoping by separate trees
Shadow DOM attaches a hidden DOM tree to a host element. Selectors in the page's stylesheets do not match elements inside that tree, and selectors inside the tree do not match the page.
<div id="host"></div>
<p>Page paragraph</p>
<style>
p { color: red; }
</style>
<script>
const root = document.getElementById("host").attachShadow({ mode: "open" });
root.innerHTML = `
<style>p { color: green; }</style>
<p>Shadow paragraph</p>
`;
</script>The page paragraph is red. The paragraph in the shadow tree is green, even though the page rule p { color: red; } would otherwise match it. This is true encapsulation, and no selector in either direction crosses the boundary.
Shadow DOM has a different shape of cost:
- It is a component-model decision, not just a styling one.
document.querySelectordoes not see inside, form participation needs extra work, and event retargeting changesevent.target. - Inherited properties, such as
colorandfont-family, and CSS custom properties still pass through the boundary. Anything else needs::part()or::slotted()hooks, or custom properties you design on purpose. - It needs JavaScript, or declarative shadow DOM in HTML, so it is heavier than a stylesheet change.
- It does not help with a plain page of normal markup, where you only want a section's
arule not to leak elsewhere.
@scope is not an alternative to Shadow DOM when you need a hard boundary. It is an alternative when you want lower-cost, same-tree scoping.
The cascade differences that matter in practice
Choosing between these tools changes how specificity and order behave.
| Behavior | BEM | CSS Modules | `@scope` | Shadow DOM |
|---|---|---|---|---|
| Specificity added by the boundary | None, by convention | None | None. The root adds nothing, but `:scope` counts as a pseudo-class. | Not applicable. Separate trees do not compete. |
| Outside rules can still match inside | Yes | Yes, for element selectors and any class an author knows | Yes | No, apart from inheritance and custom properties |
| Can exclude an inner region | No | No | Yes, with the scope limit | Not applicable. The inner region is its own tree. |
| Resolves conflicts between nested contexts | By specificity and order | By specificity and order | Scope proximity, after specificity | Not needed |
The specificity row has a practical consequence. Because @scope adds none, a plain global rule with more specificity beats it:
<div class="card"><a href="#">Read more</a></div>
<style>
.card a { color: blue; } /* specificity 0,1,1 */
@scope (.card) {
a { color: green; } /* specificity 0,0,1 */
}
</style>The link is blue. The @scope rule is lower in specificity, so proximity and order never come into play. In a BEM codebase migrating to @scope, expect old .card a rules to win until you remove them. Conversely, if you move to @scope in a large legacy stylesheet, the lack of added specificity makes your new rules easy to override by accident.
Choosing: a decision guide
Start with what actually failed. Then pick the lightest tool that covers it.
The diagram is a starting point. These criteria sharpen it:
- Boundary strength. If a widget will be embedded in pages you do not control, only Shadow DOM protects it. The others assume you control the surrounding CSS.
- Toolchain. If you cannot add a build step, such as on a static site, in a CMS theme, or in an email-adjacent environment, CSS Modules is out. BEM and
@scoperemain. - Content you do not author. Rendered Markdown and user content have bare elements.
@scope (.prose) { a { ... } }handles this cleanly. BEM cannot, and CSS Modules needs:global. - Nested components. A card that can contain another card, or a panel that hosts arbitrary widgets, benefits from the scope limit and proximity. Neither BEM nor CSS Modules has an equivalent.
- Browser support. BEM works everywhere.
@scoperequires a browser that implements it. The last chapter covers fallbacks.
Combining approaches
These are not exclusive.
@scopewith light BEM. Use@scope (.card)for the structure, and keep modifier classes such as.is-featuredfor state. You drop thecard__prefixes but keep the predictable single-class selectors.@scopeinside Shadow DOM. Rarely needed, because the shadow tree is already isolated. It can still help when a shadow tree has repeated nested regions, such as a tab panel containing another panel.- CSS Modules with
@scope. Use the module for unique root class names, and@scopefor the inner element selectors and limits.
/* panel.module.css */
@scope (.panel) to (.nested-panel) {
h3 { margin-block: 0 0.5rem; }
a { color: rebeccapurple; }
}Here .panel and .nested-panel are rewritten to unique names by the bundler, which is the case the donut handles well: the outer panel's headings and links do not reach into a panel nested inside it.
Summary of trade-offs
- BEM costs naming discipline and gives universal compatibility and flat specificity.
- CSS Modules costs a toolchain and gives strong class-name uniqueness.
@scopecosts a modern browser and gives short selectors, scope limits and proximity, but no hard isolation.- Shadow DOM costs a component architecture and gives the only real boundary.
Exercise
A team builds a marketing site as static HTML with no bundler. Pages include a blog body rendered from Markdown, which contains bare h2, a and img elements, and some blog posts embed a "callout" box that can contain its own nested blog-style content. They want blog styles not to leak into the callout. Which approach fits best, and why do BEM and CSS Modules fit worse?
Show answer
@scope (.blog) to (.callout) { ... }. There is no bundler, so CSS Modules is not available. BEM needs a class on every element, and the Markdown output has bare elements the team does not control. @scope styles bare elements by selector inside the root, and the scope limit .callout excludes the nested subtree, which gives the donut behavior they want. Shadow DOM would be heavier than needed because the page is not a component system and the team controls the surrounding CSS.
Exercise
A page has the rule .card a { color: blue; } and later in the same stylesheet @scope (.card) { a { color: green; } }. What color is a link inside .card, and why?
Show answer
Blue. The @scope rule's a selector has specificity 0,0,1 because the scope root adds none, and .card a has 0,1,1. Specificity is compared before scope proximity and order of appearance, so the later @scope rule loses.