如果您创建具有影子根的自定义元素,并使用 :host
选择器向其添加样式规则:
<style>
:host {
color: red;
}
</style>
然后使用元素选择器在自定义元素的 light DOM 中添加样式:
<style>
custom-element {
color: blue;
}
</style>
元素选择器中的样式取代 :host
选择器中的样式。可以说,这是理想的行为 - 但我很好奇为什么这是真的......如果 :host
是一个伪类,它不应该比 custom-element< 具有更高的特异性吗
,并优先?如果这是规则的异常(exception),它是否记录在规范中的某处?
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.
关于css - 为什么元素选择器取代 :host selector in custom elements with shadow DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821175/