Web Components, Shadow DOM and Iframes
On this page
The collision problem
Two teams on one page share one global stylesheet and one DOM. The catalog team writes h3 { color: red } for product names. The reviews team's headings turn red too. Someone adds .title { font-size: 40px }, and a heading in another team's widget doubles in size. Nobody broke anything on purpose. Global CSS just doesn't respect team boundaries.
You have three tools, from lightest to strongest: naming discipline, shadow DOM and iframes.
Naming discipline
The lightest fix is to never write global selectors. CSS Modules, a prefix per team (.cart-title) or a CSS-in-JS library that generates class names all keep styles scoped by convention. It costs nothing at run time and works with any composition. Its weakness is that it's only a convention: one global selector from one team, or from a third-party library, still leaks everywhere. Day 10 adds cascade layers to make that safer.
Shadow DOM
Shadow DOM gives an element its own private DOM tree with its own styles. Selectors from outside don't match inside, and styles inside don't leak out. It's part of the web components standards, together with custom elements, which let you define tags like <shop-reviews>.
The reviews team wraps their React micro-frontend as a custom element with a shadow root:
import { createRoot, type Root } from 'react-dom/client';
import { Reviews } from './Reviews';
const css = `
:host { display: block; }
.box { border: 1px solid var(--shop-border, #ccc); padding: 8px; }
h3 { color: rgb(0, 90, 160); }
`;
class ShopReviews extends HTMLElement {
static observedAttributes = ['sku'];
private root?: Root;
connectedCallback() {
const shadow = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
shadow.innerHTML = `<style>${css}</style><div></div>`;
this.root = createRoot(shadow.lastElementChild as HTMLElement);
this.render();
}
attributeChangedCallback() { this.render(); }
disconnectedCallback() { this.root?.unmount(); this.root = undefined; }
private render() {
this.root?.render(<Reviews sku={this.getAttribute('sku') ?? ''} />);
}
}
if (!customElements.get('shop-reviews')) customElements.define('shop-reviews', ShopReviews);Any page, or any other team's micro-frontend, can now write <shop-reviews sku="lamp"></shop-reviews>, whatever framework it uses. The custom element's lifecycle maps neatly onto the mount contract: connectedCallback mounts, disconnectedCallback unmounts, and attributes act as props.
What shadow DOM isolates, and what it doesn't
The lab put that element on a page whose global CSS tried hard to interfere:
:root { --shop-border: rgb(200, 0, 0); }
body { font-family: Georgia, serif; color: rgb(20, 120, 20); }
h3 { color: red; }
.title { font-size: 40px; }
.box { border: 5px dashed black; }Here's what the browser computed:
shell h3: rgb(255, 0, 0) 40px (page styles apply outside)
shadow h3: rgb(0, 90, 160) 18.72px (page h3 and .title rules blocked)
shadow p: rgb(20, 120, 20) | Georgia (inherited properties still flow in)
shadow .box border: 1px solid rgb(200, 0, 0) (page .box blocked, CSS variable flows in)
document.querySelectorAll('h3') finds: 1 (outer queries can't see inside)Three lessons hide in that output:
- Selectors are isolated. The page's
h3,.titleand.boxrules didn't touch the shadow tree. - Inheritance is not isolated.
colorandfont-familyset onbodystill flowed in, because inherited properties pass through the shadow boundary. That's usually what you want, so the widget matches the page's typography. If you need a clean slate, set:host { all: initial; }and then restore what you want. - CSS custom properties pass through.
var(--shop-border)picked up the page's value. That's the intended channel for theming: the design system defines tokens as custom properties on:root, and every shadow tree can use them (Day 10).
Changing the attribute with setAttribute('sku', 'mug') re-rendered the heading to "Reviews for mug", and removing the element unmounted the React root without errors.
Costs of shadow DOM
- Global styles can't reach in either. Your design system's CSS must be loaded into each shadow root, for example with constructable stylesheets (
adoptedStyleSheets), which can share one parsed stylesheet across many roots. - Portals and overlays. Modals and tooltips that render into
document.bodyleave the shadow root and lose its styles. Render them inside the shadow root, or use the nativepopoverattribute and<dialog>element, which render in the top layer from where they are. - Testing and accessibility tools need to understand shadow roots. Playwright pierces open shadow roots automatically. Use
mode: 'open'unless you have a reason not to. - Server rendering of shadow roots needs declarative shadow DOM (
<template shadowrootmode="open">), which adds work.
Iframes: the strongest boundary
An iframe gives a micro-frontend its own whole document: its own CSS, its own JavaScript globals, even its own copy of React. Nothing collides, and one iframe crashing can't break the page around it.
That isolation is also the cost. Each iframe is a full page load with its own memory. Sizing it to its content needs messaging. Focus, keyboard navigation and screen readers cross the boundary awkwardly. Deep linking and the back button need extra work. Communication goes through postMessage, and every message must check event.origin before trusting it.
Iframes fit specific jobs well: embedding a legacy app during a migration, running third-party or untrusted content with the sandbox attribute, or isolating something like a payment form whose provider requires it. For the main experience of a single product, web components or plain mounting are better.
Check yourself
Yes. Shadow DOM blocks outside selectors, but inherited properties like font-family and color still flow from the host element into the shadow tree. In the lab, a paragraph inside the shadow root used the page's Georgia font and green color. Use :host { all: initial; } if you need a clean slate.
As CSS custom properties defined on :root, such as --ds-primary. Custom properties pass through shadow boundaries, so components inside shadow roots can read them with var(--ds-primary). In the lab, a shadow-root border picked up the page's --shop-border value while the page's .box rule was blocked.
When you need full isolation, such as embedding a legacy app during migration, running untrusted content with sandbox, or a provider-hosted payment form. It's too heavy for a product's normal screens.
Rendering into document.body moves the modal out of the shadow root, so the styles defined inside the shadow root no longer apply. Render it inside the shadow root instead, or use the native <dialog> element or popover attribute, which display in the browser's top layer from where they are.
Defining the same tag name twice throws an error. If the micro-frontend's module is loaded more than once, for example by two versions during a rollout, the guard prevents the second definition from breaking the page.