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:
Specificity. The issue with the above example is that according to the browser's specificity algorithm,
.class1.class2is considered more "specific" than.class3. So specificity is not a good fit here, since the browser invents an illogical relationship between.class1.class2and.class3.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.
!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
!importantif I want.class3to take higher precedence in the example above?
As you've already mentioned, it comes down to Specificity. You can modify your CSS to make the
.class3entry more specific and add-on the original selector.class1.class2.class3::after, .class3::after..class1.class2.class3will override.class1.class2because the former contains the latter.I think that
!importantis 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.