Search code examples
csscss-specificity

How to add CSS specificity without relying on parent selectors or using !important?


blue should be blue without adding ids to elements, without using JavaScript and without knowing the parent #ids, as they can change at a future date, while allowing JavaScript to set style attributes that apply correctly.

custom-tag {
  color: blue; 
  /* 
   * the above should have the specificity of exactly 2×ids + 1×tag
   */
}


/*  later loaded CSS, which is not controllable... */

#one custom-tag, #two custom-tag {
  color: red;
}
<div id="one">
  <custom-tag>blue</custom-tag>
  <custom-tag style="color:orange">orange</custom-tag>
</div>

<div id="two">
  <custom-tag style="color:green">green</custom-tag>
  <custom-tag>blue</custom-tag>
</div>


Solution

  • Increase selector specificity without the need of parents, using :not() + non-existing selectors of desired specificity:

    any-tag:not(#bogus_id):not(#bogus_id) {
      color: blue; 
    }
    
    #one any-tag, #two any-tag  {
      color: red;
    }
    <div id="one">
      <any-tag>blue</any-tag>
      <any-tag style="color:orange">orange</any-tag>
    </div>
    
    <div id="two">
      <any-tag style="color:green">green</any-tag>
      <any-tag>blue</any-tag>
    </div>