How to style :root without !important using proper

2019-02-26 02:45发布

Inside a Custom Element because border-color is set on the parent page, I can not make border-color work without resorting to !important

  :host([player="O"]) {
      color: var(--color2);
      border-color: var(--color2) !important;
  }

The selector works fine, the color is set,
so it is a Specificity issue

Question: Is it possible without !important ?

Working snipppet:

window.customElements.define('game-toes', class extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({
      mode: 'open'
    });
    shadowRoot.innerHTML = 'Toes';
    shadowRoot.appendChild(document.querySelector('#Styles').content.cloneNode(true));
  }
});
:root {
  --boardsize: 40vh;
  --color1: green;
  --color2: red;
}

game-toes {
  width: var(--boardsize);
  height: var(--boardsize);
  border: 10px solid grey;
  background: lightgrey;
  display: inline-block;
}
<TEMPLATE id="Styles">
  <STYLE>
      :host {
          display: inline-block;
          font-size:2em;
      }

      :host([player="X"]) {
         color: var(--color1);
         border-color: var(--color1);
      }

      :host([player="O"]) {
        color: var(--color2);
        border-color: var(--color2) !important;
      }
  </STYLE>
</TEMPLATE>
<game-toes player="X"></game-toes>
<game-toes player="O"></game-toes>


qomponents

2条回答
太酷不给撩
2楼-- · 2019-02-26 03:27

You are using CSS variable so you can still rely on them like this:

window.customElements.define('game-toes', class extends HTMLElement {
  constructor() {
    super();
    let shadowRoot = this.attachShadow({
      mode: 'open'
    });
    shadowRoot.innerHTML = 'Toes';
    shadowRoot.appendChild(document.querySelector('#Styles').content.cloneNode(true));
  }
});
:root {
  --boardsize: 40vh;
  --color1: green;
  --color2: red;
}

game-toes {
  width: var(--boardsize);
  height: var(--boardsize);
  border: 10px solid var(--playercolor,grey);
  color:var(--playercolor,#000);
  background: lightgrey;
  display: inline-block;
}
<TEMPLATE id="Styles">
  <STYLE>
      :host {
          display: inline-block;
          font-size:2em;
      }

      :host([player="X"]) {
          --playercolor: var(--color1);
      }

      :host([player="O"]) {
          --playercolor: var(--color2);
      }
  </STYLE>
</TEMPLATE>
<game-toes player="X"></game-toes>
<game-toes player="O"></game-toes>
<game-toes ></game-toes>

查看更多
趁早两清
3楼-- · 2019-02-26 03:31

As a complement to @Temani excellent answer: it happened because the element CSS style for <games-toes> will supersede the shadow root :host style.

According to Google's 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;}

查看更多
登录 后发表回答