: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

浏览器兼容性

另见