Slotted Nodes

a.k.a distributed nodes.

Web ComponentsShadow DOMUsing Slots

  • Nodes (in light DOM) that can be inserted into <slot> are known as slottable nodes; when a node has been inserted in a <slot>, it is said to be slotted.

  • An unnamed <slot> will be filled with all of the custom element's top-level child nodes that do not have the slot attribute. This includes text nodes. 📘 Using templates and slots

  • Only custom element's top-level children (in the light DOM) may have [slot] attribute❗️ 👉 See "light DOM" tab in example code in Using Slots.

  • ::slotted() only select slotted element itself, not its descendants (content)❗️

Slotted Contents

  • slotted content come from light DOM, they use document styles❗️

  • shadow DOM styles do not affect slotted content❗️

  • ::slotted() only select slotted element itself, not its descendants (content)❗️

  • ::slotted() can't go inside light DOM, for example: ::slotted(div) p is invalid❗️

  • ::slotted() can't be used in .querySelector()❗️

👉 Styling in Shadow DOM

在下面的範例碼中,我們分別在外部內部 CSS<span> 元素做「粗體」與「紅色」格式設定,對於插入 shadow DOM<slot><span> 而言,只有外部的「粗體」設定有效 (👉 see: "codepen" tab below)。 💾 replit

<!-- ⭐️ document (outer) styles -->
<style>
  span {
    font-weight: bold
  }
</style>

<!-- ⭐️ custom element -->
<user-card>
  <!-- ⭐️ slotted element -->
  <div slot="username">
    <!--  
      ⭐️ slotted content is affected by document (outer) styles,
         not by local (shadow DOM) styles❗️  
    -->
    <span>John Smith</span>
  </div>
</user-card>

<script>
  customElements.define('user-card', class extends HTMLElement {
    connectedCallback() {
      this.attachShadow({mode: 'open'});
      
      // ⭐️ shadow tree (with named <slot>)
      // 1. slotted elements come from light DOM, they use document styles. 
      // 2. local styles do not affect slotted content.
      this.shadowRoot.innerHTML = `
        <style>
          span { background: red; }
        </style>
        Name: <slot name="username"></slot>
      `;
    }
  });
</script>

Styling Slotted Content

💾 ::slotted() lab

  • use document (outer) styles (in light DOM).

  • style <slot> (in shadow DOM) and rely on CSS inheritance.

  • use ::slotted(«selector») in shadow DOM.

Last updated