:has-slotted

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

:has-slotted CSS 偽類<slot> 元素的內容不為空或沒有使用預設值時(參見使用模板和插槽瞭解更多資訊)匹配。

注意: 即使只有一個空白文字節點,也足以使 :has-slotted 生效。

這隻在 Shadow DOM 中使用的 CSS 裡有效。

css
/* Selects the content of a <slot> element that has content that is not default  */
:has-slotted {
  color: green;
}

/* Selects the content of a <slot> element that has no content or default  */
:not(:has-slotted) {
  color: red;
}

語法

css
:has-slotted {
  /* ... */
}

示例

此示例包含兩個 <slot> 元素,其中一個已分配了內容,另一個未分配內容。

HTML

html
<p>
  <template shadowrootmode="open">
    <style>
      :has-slotted {
        color: rebeccapurple;
      }
    </style>
    <slot name="one">Placeholder 1</slot>
    <slot name="two">Placeholder 2</slot>
  </template>
  <span slot="one">Slotted content</span>
</p>

結果

已分配內容的 <slot> 元素匹配了 :has-slotted 偽類,並應用了 rebeccapurplecolor 值。

規範

規範
CSS 作用域模組級別 1
# the-has-slotted-pseudo

瀏覽器相容性

另見