我们在一个通用样式文件中拥有CSS重置(margin:0px;padding:0px;)
,我们将其编写为一个组件,并将其作为我们正在开发的其他组件的一部分。
我们正在使用如下所示的通用选择器
*,*:before,*:after{
color:pink
}
在我们的每个组件上,我们都有一个:host
样式,我们试图用它来覆盖这种颜色
:host{
color:yellow
}
正如我们期望的那样,:host
在通用选择器方面具有更多的特异性,但事实并非如此。通用选择器样式覆盖了我们的:host
样式
我们只想让组件z-foo成为我的绿色(在随附的plnkr示例中)
尝试了多种方法,似乎没有任何效果
http://plnkr.co/edit/l8NSJT?p=preview
其粉红色表示仍被通用选择器覆盖
<!-- import polymer-element -->
<link rel="import" href="https://polygit.org/polymer+:2.0-preview/webcomponentsjs+:v1/shadydom+webcomponents+:master/shadycss+webcomponents+:master/custom-elements+webcomponents+:master/components/polymer/polymer-element.html">
<dom-module id='z-foo'>
<template>
MAKE ME GREEN
<!-- Encapsulated, element-level stylesheet -->
<style>
:host{
color:green;
}
</style>
<div>
I'm z-foo and i am green.
</div>
</template>
<script>
class ZFoo extends Polymer.Element {
static get is() {
return "z-foo";
}
}
customElements.define(ZFoo.is, ZFoo);
</script>
</dom-module>
正如我们期望的那样,
:host
在通用选择器方面具有更多的特异性,但事实并非如此。通用选择器样式覆盖了我们的:hoststyles
这是错误的假设。实际上,包含文档中定义的任何CSS选择器都将覆盖:host
CSS规则。
根据Google的Shadow DOM presentation:
外部样式始终胜过影子DOM中定义的样式。例如,如果用户编写选择器
fancy-tabs { width: 500px; }
,它将胜过组件的规则::host { width: 650px;}
作为解决方法,根据需要将!important
与:host
结合使用。