css - 为什么元素选择器取代 :host selector in custom elements with shadow DOM

标签 css css-selectors shadow-dom css-specificity

如果您创建具有影子根的自定义元素,并使用 :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/

相关文章:

css - 无法显示所有这些内联!

html - 是否有选择器以特定网格位置的元素为目标?

css - 内部类的属性的 SaSS 语法?

performance - 使用 FAST 有没有办法将样式应用于 ShadowDOM 子元素?

javascript - 在 native DOM 中,有没有办法将两个节点组合起来形成一个范围以供查询?

javascript - 试图防止图像在 Bootstrap 轮播中被拉伸(stretch)

html 元素 : newline after but do not expand

html - 一个div中的三个跨度,最右边的跨度占据所有宽度

css - 可选的子选择器,带 CSS/Stylus/LESS : . aa > .bb? > .cc

javascript - ShadowDOM v1 - 在 lightdom 中更改输入文本