When to use !important in CSS

Never!

CSS has a feature called !important. What it does is force a property to be used, regardless of other properties that are more specific. It can be very handy.

Let me show you:

HTML:
<div class="button-area">
    <a href="#" class="btn">Click Me</a>
</div>

CSS:
.button-area a {
    color: red;
}
.btn {
    color: green;
}

What color is the word Click Me going to be? If you have guessed red, then you are correct. Even though the color green is set after, the first one is applied because it is more specific. If I wanted the button to turn green, I would have to use the keyword !important to force CSS to use this property instead.

.btn {
    color: green !important; /* ignore other rules, use me! */
}

So here is my suggestion on when to use the !important property. Never use the !important property. Let me explain.

If we use the keyword here in our example, every single element that has the .btn class will turn green. And in order to make sure they don't, we have to create a more specific CSS rule and add the old color back with another !important added to it.

.button-area a {
    color: red;
}
.btn {
    color: green !important; /* ignore others, use me! */
}
.button-area a.btn {
    color: red !important; /* no ignore him, use me! */
}
.button-area .btn {
    color: yellow; /* nobody cares about me */
}

So instead of adding the keyword !important it's better to reevaluate the HTML structure and rewrite a good part of the CSS to make sure the rules are well organized. For our example, we can rewrite both the HTML and CSS by adding an extra class to set this specific one to green.

HTML:
<div class="button-area">
    <a href="#" class="btn btn-secondary">Click Me</a>
</div>

CSS:
.btn {
    color: red;
}
.btn.btn-secondary {
    color: green; /*I'm more specific, so I'm in charge */
}

Now you may ask, "Ibrahim, I checked your page source and I found the keyword !important in it. Why did you use it?"

My answer is, I used it as a band-aid until I can rewrite that part of the CSS. When I'm asked, my answer is always Never use !important because it leads you down a rabbit hole you won't be able to get out off.

I use the same philosophy when it comes to using position: absolute; I always tell people never to use it. The reason is, if you rely on it to position one element, you'll quickly find yourself in that rabbit hole again where you have a hierarchy of absolutely positioned elements that are entangled together. Removing one elements destroys all your CSS. The solution is to never use it. In the rare cases you have to use it, Don't use it!

This forces you to explore every alternative before making use of these expensive properties. And when you end up using them, you know exactly why you had to.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only