cssweb-componentcustom-elementcss-specificity

How to style :root without !important using proper specificity


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


Solution

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