csscss-selectorscss-specificity

How to increase priority without using !important?


How do I get rid of the !important tag in the following example?

<html><head><style>

  .class1.class2::after {
    content: ".class1.class2";
  }
  .class3::after {
    content: ".class3" !important;
    /* how do we make this higher priority without "!important"? */
  }
  

td {padding-right: 20px;}

</style></head>
<body>

<table>
<tr><td>class1 class2</td><td><div class="class1 class2"></div></td></tr>
<tr><td>class1 class2 class3</td><td><div class="class1 class2 class3"></div></td></tr>
</table>

</body></html>

I am aware of 3 rule precedence mechanisms in CSS:

  1. Specificity. The issue with the above example is that according to the browser's specificity algorithm, .class1.class2 is considered more "specific" than .class3. So specificity is not a good fit here, since the browser invents an illogical relationship between .class1.class2 and .class3.

  2. Declaration order appears not to work either: since specificity takes precedence over declaration order, it does not matter what order the rules are written in.

  3. !important. But it is frowned upon (if you can educate me on why it's frowned upon, that might give us some insight). Can I avoid !important if I want .class3 to take higher precedence in the example above?


Solution

  • As you've already mentioned, it comes down to Specificity. You can modify your CSS to make the .class3 entry more specific and add-on the original selector .class1.class2.class3::after, .class3::after.

    .class1.class2.class3 will override .class1.class2 because the former contains the latter.

    I think that !important is frowned upon purely because it's seen like a bit of a hack/workaround to force a particular style in the absence of properly formatted and written CSS.

    <html>
    
    <head>
      <style>
        .class1.class2::after {
          content: ".class1.class2";
        }
        
        .class1.class2.class3::after,
        .class3::after {
          content: ".class3";
        }
        
        td {
          padding-right: 20px;
        }
      </style>
    </head>
    
    <body>
    
      <table>
        <tr>
          <td>class1 class2</td>
          <td>
            <div class="class1 class2"></div>
          </td>
        </tr>
        <tr>
          <td>class1 class2 class3</td>
          <td>
            <div class="class1 class2 class3"></div>
          </td>
        </tr>
      </table>
    
    </body>
    
    </html>