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

问题描述 投票:0回答:2

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

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

<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)) { }
```
css web-component shadow-dom
2个回答
4
投票

有趣的转变,这是可能的,直到

exportparts

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts

示例1

<style>
  mux-player::part(textspan) { color: red; }
</style>

<mux-player>
  <template shadowrootmode="open">
    <media-poster-image exportparts="poster, img, innerspan: textspan">
      <template shadowrootmode="open">
        <img part="poster img" src="...">

        <span part="innerspan">
          This text will be red because the containing shadow host forwards innerspan to the document as "textspan" and the document style matches it.
        </span>

        <span part="textspan">
          This text will not be red because textspan in the document style cannot match against the part inside the inner custom element if it is not forwarded.
        </span>
      </template>
  </template>
</mux-player>

示例2

生产中的示例,其中包含多个带有 CSS 部分的嵌套自定义元素。
https://github.com/muxinc/elements/blob/main/packages/mux-player/src/template.ts


3
投票

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

::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 结合使用。无论组件的用户设置什么类/上下文,您都可以更改嵌套子组件的样式。

顺便说一句,即使不使用 Shadow DOM 或 Web 组件,修改颓废组件(子组件的子组件)的样式也是一种不好的做法。这会导致 CSS 变得脆弱且不可维护。

编辑注:

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

© www.soinside.com 2019 - 2024. All rights reserved.