Hugo Lyra
Hugo Lyra


Hugo Lyra

Why you should forget about !important?

Why you should forget about !important?

Hugo Lyra's photo
Hugo Lyra
·May 11, 2021·

2 min read

Let start with one story, today you should work on that task to change the color of a label, peace of cake. You seat comfortable on your desk and create that class to the label.

.red-label { color: red; }

Start the build and for your surprise the label is still with an ugly green, you start debug the code and realize there is other rule in the code.

.container label { color: green !important; }

Find the problem, let's fix:

.red-label { color: red !important; }

Now it's working, everybody is happy, right? Wrong!

What is the problem and how to fix it?

Overspecifing rules will lead to hard maintainability and code readability, while there is no real benefit.

CSS stands for Cascading Style Sheets, which means, if you apply different color for a label several times in your CSS with the same specificity, the selector which is further down in the source will apply.

How to calculate specificity

  1. Count the number of ID attributes in the selector
  2. Count the number of other attributes and pseudo-classes in the selector
  3. Count the number of element names in the selector

The !important value appended to a CSS property value is an automatic win, it overrides even inline styles from the markup. The only way an !important value can be overridden is with another !important rule declared later in the CSS, since the hierarchy that defines which property should be applied to which element.

One thing that may help on use correct specificity try using BEM or other similar naming methodologies and the general rule is always think on your CSS hierarchy.

Thanks for reading!

Share this