This post however is not about some grand design patterns - it’s about a very specific part of stylesheet design that often gets overlooked or misused. I’m talking about the
!important postfix in CSS declarations.
The concept itself is dead simple: a rule that is declared important overrides other rules regardless of which rule has more specific selector. It is also equally obvious that the
!important keyword is easy to abuse and can really mess up your code base when used excessively.
The thing I wasn’t so sure about was when one should use
!important. After some thinking I came up with a few examples that describe the use cases quite well. The first and possibly the most common use case that benefits from
!important is a class for hiding an element from the end user.
Without the postfix it would be very easy to accidentally overwrite the
display attribute - for example by simply using
table layout on an element with the class. The selector for
display: none would have to be pretty specific to avoid the overwrite.
The next example propably calls for a bit more explaining. You could also call it a utility class of some sort but I’d rather call it a component class. The word component carries many connotations in web development but I feel it’s the word that best describes the use case where the class represents a singular element of design.
In the example above, the HTML element with the
button class isn’t necessarily a
<button> element. If the button acts as a link, it should be one. That means using an
<a> element. As with the hiding example, one can run into trouble when selectors more specific than the utility one are introduced. With the button example the problem may show up with any attributes used. For example, certain links should be underlined - unless they are buttons. Once again the
!important comes to rescue.
As we see, some times the cause really is important enough to justify the use of
!important. The examples above most certainly aren’t the only situations where the postfix is a good idea. Still, most of the times I’ve seen it used in live code the code would have been better off without it. Thus the title.
!important declaration packs great power and thus comes with a great responsibility. Be careful or one day you’ll find yourself overwriting
!important rules with more specific
!important rules. You don’t want to end up there.