🔸slotted nodes

a.k.a distributed nodes.

webcomponentslot ⟩ slotted nodes

任何在自訂 web component 標籤(如:<my-component>)之間的直接子元素(direct child),包含文字(text node),都是 slotted nodes,例如:

<my-component>
  <!-- ⭐️ slotted nodes -->
  <!-- ⭐️ 沒有指定 slot -->
  <p>This is a slotted node.</p>
  <!-- ⭐️ 指定 slot="username" -->
  <div slot="username"><span>John Smith</span></div>
</my-component>
  • 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

Slotted Contents

👉 Styling in Shadow DOM

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

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

Was this helpful?