:host getting oveerirden by universal selector css

▼魔方 西西 提交于 2020-05-23 21:32:08

问题


We have CSS resets (margin:0px;padding:0px;) in a common style file which we have authored as one component and have included as a part of other components which we are developing.

We are using universal selectors like below

*,*:before,*:after{
color:pink

}

On each of our component we have a :host style with which we are trying to override this color

:host{
color:yellow
}

As we expect :host to have more specificity over universal selector strangely this is not the case. universal selector styles are overriding our :hoststyles

We just want MAKE ME GREEN styled from component z-foo (in the attached plnkr example)

Tried multiple approaches and nothing seems to work

http://plnkr.co/edit/l8NSJT?p=preview

Its pink which means its still gets overridden by universal selector

        <!-- 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>

回答1:


As we expect :host to have more specificity over universal selector strangely this is not the case. universal selector styles are overriding our :hoststyles

It's a wrong asumption. Actually, any CSS selector defined in the containing document will override the :host CSS rules.

According to Google's Shadow DOM presentation:

Outside styles always win over styles defined in shadow DOM. For example, if the user writes the selector fancy-tabs { width: 500px; }, it will trump the component's rule: :host { width: 650px;}

As a workaround, use !important combined with :host if you need.



来源:https://stackoverflow.com/questions/58371333/host-getting-oveerirden-by-universal-selector-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!