CSS :part 伪选择器可以用于设置嵌套 Web 组件的样式吗?

Can the CSS :part pseudo-selector be used to style nested web components?

使用 Shadow DOM 创建具有封装样式的 Web 组件时,可以使用 ::part 伪选择器 (https://developer.mozilla.org/en-US/docs/Web/CSS/::part) 设置部分阴影标记的样式。

部件选择器可以用于定位嵌套的阴影部件吗?

<custom-element>
  #shadow-root
    <div part="thats-easy"></div>
    <another-custom-element part="proxy-part">
      #shadow-root
        <div part="target-me"></div>
    </another-custom-element>
</custom-element>

目前的努力没有结果:

another-custom-element::part(target-me) { }
custom-element::part(proxy-part) another-custom-element::part(target-me) { }
custom-element::part(proxy-part another-custom-element::part(target-me)) { }
custom-element::part(proxy-part::part(target-me)) { }
```

没有。这不可能。它打破了封装原则。正确的方法是使用适当的主题。这意味着使用以下组合:

::part - For direct theming of the component
:host-context - for theming based on the context
::slotted - For styling the slotted element inside the styling

要获得更动态的主题,您可以将上述样式与 Element.matches API 结合使用。无论组件的用户设置了什么 class/context,您都可以更改嵌套子组件的样式。

On a side note, modifying the styling of a decadent component (children of children) is a bad practice even when not using Shadow DOM or Web Components. It will result in a brittle non-maintainable CSS.

编辑备注:

:host-context 并未在所有浏览器中实现,而且可能永远不会实现。