A custom card attaches a shadow root so its internal style and markup are scoped away from the outer page.

Program

Shadow DOM gives a component a private subtree. Styles inside that subtree target the component internals without leaking out.

shadow_dom_card.html
Visuals: captured from real browser rendering
<section id="host"></section>
<script>
  const host = document.querySelector("#host");
  const shadow = host.attachShadow({ mode: "open" });
  shadow.innerHTML = `<style>.card { color: white; background: #0f766e; }</style>
    <article class="card">Scoped card</article>`;
</script>
  1. Create the component host.

    The host is the visible attachment point for the component.
    The host is the visible attachment point for the component.
  2. Find the host element.

    JavaScript needs the host before it can attach a shadow root.
    JavaScript needs the host before it can attach a shadow root.
  3. Attach an open shadow root.

    The host now owns a private subtree.
    The host now owns a private subtree.
  4. Write scoped styles.

    The .card rule applies inside the shadow root.
    The .card rule applies inside the shadow root.
  5. Render component markup.

    The article appears through the host but lives in the shadow tree.
    The article appears through the host but lives in the shadow tree.
attachShadow attachShadow creates a shadow root on a host element.
style scope Styles in shadow DOM apply to the shadow tree, not the outer document.