slot element

A slot is an insertion point in a Shadow DOM template. It lets a custom element accept content from the Light DOM while keeping its internal structure encapsulated.

What you will learn

What does slot do?

Shadow DOM hides a component's internal tree from ordinary page styles and markup. A slot creates a deliberate opening where child content supplied by the component user can appear.

A default slot

const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `<article>
  <slot>No content supplied.</slot>
</article>`;

// Light DOM
<my-card><p>Content from the page</p></my-card>

Because the slot has no name, eligible child nodes go into the default slot. The text inside the slot is fallback content and appears only when nothing is assigned.

Named slots

Use a name when a component has multiple insertion points. The child in the Light DOM uses a matching slot attribute.

Header and body slots

// Shadow DOM template
<header><slot name="title">Default title</slot></header>
<main><slot>Default body</slot></main>

// Light DOM
<my-card>
  <h2 slot="title">Account</h2>
  <p>Your settings</p>
</my-card>

A typo in either the slot name or the slot attribute sends content to the wrong place or leaves fallback content visible. Treat slot names as part of the component's public API.

Styling slotted content

Styles inside the Shadow DOM are encapsulated. A component can style assigned elements with ::slotted(), but that selector only reaches the direct slotted element, not every descendant inside it.

A limited slotted selector

::slotted(p) {
  margin-block: 0;
  color: var(--card-text, inherit);
}

Design checklist

Related pages