如何 select :host with a class in css for web components?

How to select :host with a class in css for web components?

在新的 v1 网络组件规范中,您可以使用 :host 来定位自定义元素。但是后来我将 class A 附加到自定义元素,并有一个 css 选择器 :host.A,但它的样式没有被应用。有谁知道如何解决这个问题?

谢谢

根据 documentation:

For example, say you had a component with a shadow tree like the following:

<x-foo class="foo">
    <"shadow tree">
        <div class="foo">...</div>
    </>
</x-foo>

For a stylesheet within the shadow tree:

  • ...
  • ':host(.foo)' matches the <x-foo> element.

正如 OP 评论的那样,在这种情况下,这将转化为:

:host(.a) {
    ...
}

也许这不应该起作用,但对我来说它确实有效:

:host-context(.dialog) .overlay { background: green; }

对于 class,直接附加到模板(不是更高的东西)

<my-component class='dialog><div class='overlay'></div></my-component>