> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/component/template/slot/slotted-elements.md).

# slotted nodes

[web](/web/master.md) ⟩ [component](/web/component.md) ⟩ [slot](/web/component/template/slot.md) ⟩ slotted nodes

{% hint style="info" %}
任何在自訂 [web component](/web/component.md) 標籤(如：<mark style="color:blue;">`<my-component>`</mark>)之間的<mark style="color:yellow;">直接子元素</mark>(direct child)，包含文字(text node)，都是 *<mark style="color:purple;">**slotted nodes**</mark>*，例如：

```html
<my-component>
  <!-- ⭐️ slotted nodes -->
  <!-- ⭐️ 沒有指定 slot -->
  <p>This is a slotted node.</p>
  <!-- ⭐️ 指定 slot="username" -->
  <div slot="username"><span>John Smith</span></div>
</my-component>
```

{% endhint %}

{% tabs %}
{% tab title="👥 相關" %}

* [\<slot>](/web/component/template/slot.md)
* [named slot](/web/component/template/slot/named-slot.md)
* [Styling in Shadow DOM](/web/component/shadow-dom/styles.md#cheat-sheet) ⟩ **::slotted()**
* [**Use CSS Variables**](/web/component/shadow-dom/styles/css-vars.md)
  {% endtab %}

{% tab title="📗 參考" %}

* 📗 JS.info ⟩ [Styling slotted content](https://javascript.info/shadow-dom-style#styling-slotted-content)
* 👉 [Styling in Shadow DOM](/web/component/shadow-dom/styles.md#cheat-sheet) - :host, :host(), :host-context(), ::slotted()
  {% endtab %}

{% tab title="📘 手冊" %}

* MDN ⟩ [Using templates and slots](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots)
  {% endtab %}
  {% endtabs %}

{% hint style="info" %}

* Nodes (in **light DOM**) that can be **inserted** into **\<slot>** are known as ***slottable*****&#x20;nodes**; when a node **has been inserted** in a \<slot>, it is said to be ***slotted***.<br>
* An **unnamed** [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) will be **filled with** all of the **custom element'**&#x73; **top-level child nodes** that **do not have** the [`slot`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#attr-slot) attribute. This **includes text nodes**.\
  📘 [Using templates and slots](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots#adding_flexibility_with_slots)
  {% endhint %}

{% hint style="danger" %}

* 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](/web/component/shadow-dom/slots.md#code-example).
* **::slotted()** only select **slotted element** itself, **not its descendants** (content)❗️
  {% endhint %}

## Slotted Contents

{% hint style="warning" %}

* **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()**❗️
  {% endhint %}

👉 [Styling in Shadow DOM](/web/component/shadow-dom/styles.md#pseudo-class)

在下面的範例碼中，我們分別在**外部**及**內部 CSS** 對 **`<span>`** 元素做「**粗體**」與「**紅色**」格式設定，對於插入 **shadow DOM`<slot>`** 的 **`<span>`** 而言，只有**外部**的「**粗體**」設定有效 (👉 see: "**codepen**" tab below)。 💾 [replit](https://replit.com/@pegasusroe/slotted#index.html)

{% tabs %}
{% tab title="html" %}

```markup
<!-- ⭐️ 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>
```

{% endtab %}

{% tab title="codepen" %}
{% embed url="<https://codepen.io/lochiwei/pen/LYLeRWZ>" %}

{% endtab %}
{% endtabs %}

### Styling Slotted Content

💾 [::slotted() lab](https://replit.com/@pegasusroe/slotted-lab#index.html)

* use document (**outer**) styles (in **light DOM**).
* style **\<slot>**  (in **shadow DOM**) and rely on **CSS inheritance**.
* use **::slotted(«selector»)** in **shadow DOM**.

{% hint style="info" %}

* ⭐️ use **CSS variables**: \
  CSS variables exist **on all levels**, **both in light and shadow**.\
  👉 [CSS hooks with custom properties](https://javascript.info/shadow-dom-style#css-hooks-with-custom-properties)
  {% endhint %}

{% tabs %}
{% tab title="codepen" %}
{% embed url="<https://codepen.io/lochiwei/pen/mdwpRgO>" %}

{% endtab %}

{% tab title="::slotted() lab" %}

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

  /* ⭐️ select <span> in slotted <p> element */
  p[slot] span {
    background: hsl(90, 90%, 80%);    /* light green */
    padding: 0 8px;
  }
</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>

<user-card>
  <span slot="username">Jane Smith</span>
</user-card>

<user-card>
  <p slot="username">
    <span>Doctor Who</span>
  </p>
</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.
      // 3. ::slotted() only select slotted element itself, not its descendants❗️
      this.shadowRoot.innerHTML = `
                <style>
                    :host {
                        border: 1px solid black;
                        margin: 4px;
                        padding: 4px;
                        display: inline-block;
                        box-shadow: 
                            0 4px 8px 0 rgba(0, 0, 0, 0.4), 
                            0 6px 20px 0 rgba(0, 0, 0, 0.19);
                    }
                    :host(:hover) {
                        box-shadow: 
                            0 2px 4px 0 rgba(0, 0, 0, 0.6), 
                            0 3px 10px 0 rgba(0, 0, 0, 0.35);
                    }
                    ::slotted(*) {
                        border: 1px solid black;
                    }
                    ::slotted(span) { 
                        background: pink;
                        padding: 0 6px;
                    }
                    ::slotted(div) {
                        padding: 0 6px;
                        background: hsl(225, 80%, 90%);
                    }
                </style>
                Name: <slot name="username"></slot>
            `;
    }
  });
</script>
```

{% endtab %}

{% tab title="css var demo" %}

```markup
<style>
  /* ⭐️ 2. set css var with custom value */
  user-card {
    --user-card-field-color: green;
  }
</style>

<template id="tmpl">
  <style>
    /* ⭐️ 1. use css var with default value */
    .field {
      color: var(--user-card-field-color, black);
    }
  </style>
  <div class="field">Name: <slot name="username"></slot></div>
  <div class="field">Birthday: <slot name="birthday"></slot></div>
</template>
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/component/template/slot/slotted-elements.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
