DEV Community

Cover image for Why you should forget about !important?

Why you should forget about !important?

Hugo Lyra
Hi there, Iā€™m Hugo. Software Developer and an apprentice
Originally published at 惻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; }
Enter fullscreen mode Exit fullscreen mode

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; }
Enter fullscreen mode Exit fullscreen mode

Find the problem, let's fix:

.red-label { color: red !important; }
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (2)

afif profile image
Temani Afif

The specificity calculation doesn't really use points the way you described. Considering your logic, if we have 11 classes we will get 11*10=110 points and this will be bigger than the 100 points of the ID but still the ID will win.

This is a well known confusion in many articles (and a well known SO question around the subject:

Refer to the official specification for accurate detail about the calculation: you will see that we calculate 3 components and we do a comparaison one by one.

hugolyra profile image
Hugo Lyra Author • Edited

Thanks, update with what I learn from you ;)

Forem Open with the Forem app