如何风格 :root 没有 !important 使用适当的特异性

How to style :root without !important using proper specificity

自定义元素 中,因为 border-color 是在父页面上设置的,所以如果不求助于 !important,我无法使 border-color 工作

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

选择器工作正常,颜色已设置,
所以这是一个特异性问题

问题:没有!important可以吗?

工作片段:

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

您正在使用 CSS 变量,因此您仍然可以像这样依赖它们:

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>

作为对@Temani 优秀答案的补充:发生这种情况是因为 <games-toes> 的元素 CSS 样式将取代影子根 :host 样式。

根据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;}