为什么元素选择器取代带有阴影的自定义元素中的 :host 选择器 DOM

Why do element selectors supersede the :host selector in custom elements with shadow DOM

如果您创建一个带有影子根的自定义元素,并使用 :host 选择器向其添加样式规则:

<style>
    :host {
        color: red;
    }
</style>

然后使用元素选择器在 DOM 中为自定义元素添加样式:

 <style>
    custom-element {
        color: blue;
    }
</style>

元素选择器中的样式取代 :host 选择器中的样式。这可以说是理想的行为 - 但我很好奇为什么这是真的......如果 :host 是一个伪-class,它不应该比 custom-element 具有更高的特异性,并且取得优先权?如果这是规则的例外情况,是否在某处的规范中记录了它?

See JsFiddle Example

这是真的,因为它是您所说的理想行为。

它按照 CSS Scoping Module Level 1 规范的要求实现:

When comparing two declarations that have different tree contexts, then for normal rules the declaration earlier in the shadow-including tree order wins, and for important rules the declaration coming later in the shadow-including tree order wins.

Note: This is the opposite of how scoped styles work.

除了@Supersharp 所说的,还可以这样想:

:host 的使用类似于所有内置元素的浏览器默认样式。

当您添加 ANY CSS 时,您将覆盖默认值。

这就是 CSS 的工作原理,我很高兴它能做到。