Skip to content

Shadow DOM

Key idea:

Shadow DOM — technology for creating an isolated DOM subtree inside an element. CSS from the outer document does not bleed in (except inheritable properties), and outside JS querySelector cannot see the shadow tree. Foundation of the Web Components standard. Used by: YouTube Player, Google Docs, CodePen embeds, Shopify Polaris.

Below: details, example, related terms, FAQ.

Try it now — free →

Details

  • Mode: open (shadowRoot accessible) / closed (hidden)
  • Style encapsulation: CSS inside does not leak out, outside does not leak in
  • : placeholder for light DOM content projection
  • ::part() and :host: CSS API for styling shadow from outside
  • Browser support: 100% modern browsers (2019+)

Example

class MyCard extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `
      <style>
        p { color: red; }  /* scoped */
      </style>
      <p><slot>Default</slot></p>
    `;
  }
}
customElements.define('my-card', MyCard);

Related Terms

Learn more

Frequently Asked Questions

Shadow DOM vs iframe?

Shadow: same JS context, same origin, lightweight. iframe: full browsing context, heavyweight, cross-origin isolation. Shadow for widgets, iframe for third-party untrusted content.

Does React use it?

Usually no (React virtual DOM is enough). But a React web components wrapper might. Material UI v6 optionally.

CSS styling from outside?

::part() for exposed parts, :host for host element, CSS custom properties inherit. Tailwind via ::part — possible.