DOM & EventsBaseline · Widely

Shadow DOM Encapsulation and Event Retargeting

Mental Model

Shadow DOM attaches an isolated DOM and CSS subtree to a host element. Outer stylesheets cannot pierce the boundary, light-DOM children project into <slot> placeholders, and composed DOM Events crossing outward have event.target rewritten to the host element.

Interactive Simulator

Shadow Boundary Style Scoping & Event Retargeting

Trace how composed events retarget from an inner shadow button to the shadow host.

<button.save> (Shadow)
ShadowRoot Boundary
Document Listener
Step 1 / 3: 1. Inner Click Fires in Shadow Tree

Inside shadowRoot, event.target is the internal <button> element.

// Inside shadowRoot: e.target === innerButton
Internal State / Memory
phase
AT_TARGET (shadow)
eventTarget
<button.save>
composed
true

Under the Hood

Blink attaches a ShadowRoot as an encapsulated subtree whose styles and IDs are scoped away from document selectors, then merges <slot> placeholders with light-DOM children in the flat tree for layout. When a composed event bubbles past the ShadowRoot boundary, the engine rewrites event.target to the host element.

  1. Flat Tree Composition: The layout engine merges <slot> elements with slotted light-DOM children without moving nodes in the actual DOM.
  2. Hard Style Boundary: Document selectors stop at the ShadowRoot; only inheritable properties (color, font) and CSS custom properties cross inward, unlike CSS Cascade Layers.
  3. Event Retargeting: Built-in UI events (click, input) have composed: true and retarget e.target to the host; custom events default to composed: false and stop at the boundary.
HTML
<ui-badge>
  <template shadowrootmode="open">
    <style>:host { display: inline-flex; border: 1px solid; }</style>
    <slot></slot>
  </template>
  Verified
</ui-badge>

Problem Genealogy

  • 2013 (Shadow DOM v0): Blink-only prototype with /deep/ and >>> combinators that leaked styles anyway.
  • 2016 (Shadow DOM v1): Removed piercing combinators, standardized <slot> and attachShadow({ mode }).
  • 2024 (Declarative Shadow DOM): <template shadowrootmode="open"> enabled SSR without waiting for JS hydration.

Production Pitfalls

Production Pitfall
  • Broken for/aria-labelledby IDs: ID references cannot cross ShadowRoot boundaries; keep labels and inputs in the same tree, and attach any MutationObserver directly to the shadow root if you need to observe internal changes.
  • Lost Design-System Typography: Global CSS resets (button { font: inherit }) do not enter shadow trees; share tokens via CSS custom properties or constructable adoptedStyleSheets.
When Not to Use
  • When not to use Shadow DOM: Never wrap ordinary application pages or forms in Shadow DOM, it breaks global form submission, accessibility IDs, and utility CSS unless paired with ElementInternals.

Connections & Logical Next Steps

Mechanical Comparisons