๐Ÿ”ธslotted nodes

a.k.a distributed nodes.

web โŸฉ component โŸฉ slot โŸฉ 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

  • 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