← Concepts

阅读中文版本

Shadow DOM

Shadow DOM attaches an encapsulated DOM subtree with scoped styles and controlled slot-based content distribution, letting widgets ship markup that cannot clash with the host page.

browser

Definition

Shadow DOM is an encapsulation primitive that attaches a hidden subtree to an element. Styles inside the shadow root do not leak out, host page selectors do not leak in except through defined custom properties and parts, and slotted content distributes through slot elements while retaining page scope for styling purposes.

Context and scope

Used by design-system components, video player controls, and browser-native widgets. Foundation for reusable web components alongside custom elements and templates.

Common misconceptions

  • Shadow DOM hides markup from JavaScript — the tree is traversable with APIs; encapsulation is style and composition scoping, not secrecy
  • Global CSS can never affect shadow content — inheritable properties and custom properties pierce the boundary by design
  • Slots copy content into the shadow tree — slotted nodes stay in the light DOM, and CSS sees them from the page side

Anti-patterns

  • Wrapping everything in shadow roots and losing all theming because custom properties were never designed
  • Querying the page DOM for elements that live inside a closed shadow root and silently finding nothing
  • Deep selector penetration with piercing combinators where custom properties and parts would be the contract

Related concepts

Related examples

Authoritative source

https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM

What it is

A shadow root creates a second, scoped style universe attached to a host element. Inside it, selectors match only inside; outside rules do not apply. Content flows in through slots, so the page provides children and the component decides placement. The result is components that cannot be broken by page CSS accidentally.

How it works

Open and closed modes differ only in whether JavaScript can reach shadowRoot from the host. Inheritable properties like font and color still cross the boundary; custom properties explicitly pass design tokens in; the part attribute exposes styled hooks to the page. Events retarget at the host by default, with composed events crossing outward.

When to use it

Design systems distributed across many teams and apps, embeddable widgets on third-party pages, and anywhere page CSS should not dictate internal structure. Pair with custom elements for lifecycle and with externalized token contracts for theming.

Pitfalls

Theming must be designed: tokens, parts, and reflected attributes, or consumers will fight the encapsulation. Form participation historically required extra wiring. Testing tools need shadow-aware selectors, since plain querySelector cannot see inside closed roots.