Blog

Should you use !important in CSS?

I feel like this was a popular subject back in the day (2010-2012), but it’s not that important now. Get it?
Anyway, here are some articles that talked about this issue in the past: here, here and here.

What it’s !important?

You can call !important a directive, a keyword, declaration, and it’s placed at the end of a CSS propriety to prioritize it, to add more weight to it over other proprieties that might be in the way.

CSS (Cascading Style Sheets) passes along some of the proprieties from the parent to child and so on. Similar to a cascade, if it wasn’t obvious enough.

In some cases, you need to overpower those proprieties and for different reasons, you end up using the !important solution.

					

.container h2 {
  font-weight: 600;
}

h2 {
  font-weight: 300 !important;
}

In the example above your h2 will take the font-weight of 300, even inside the .container element, because it has the use of !important.

This should give you a good idea of how it works.

When will you use !important?

You might end up using !important for different reasons.

A few that I might think of:

  • Old code where you don’t know what else will be affected and you prefer to add an !important to fix your style and move on with your day
  • Dealing with inline CSS added by some 3rd party JS
  • Classes that are overlapping with another plugin or theme
  • You are using a framework (Bootstrap)

It’s not always justified, but most of the times it will be an easy way to fix something.

I try to go out of my way and get it fixed correctly without using !important. Try using an extra class when you identify the element, let !important be the last resort.

Bootstrap and frameworks

When you use frameworks on your project, you might be forced on using the !important propriety more that you want.

Comment on CSS !important and Bootstrap from smashingmagazine.com

One way to avoid this is to learn more about CSS Specificity. This will allow you to style your files better without abusing !important just to get the things done as you want.

Dark/Night Mode and !important

I can think of one example that will make the use of !important justified: Night Mode or Dark Mode.

Let’s say you want your site to have a Night Mode option, a simple switch that will change all the content into a dark background and white text.

You can have a simple switch that will add an .dark-mode-on class to the body and after that use a code similar to this:

					

body {
  background: #fafafa;
}

h2 {
  color: #dea62f;
}

p {
  color: #333;
}

.dark-mode-on {
  background: #000!important;
  color: #fff!important;
}

.dark-mode-on h2 {
  color: #fff!important;
}

Conclusion

Yes, you should use !important, just be sure not to end-up with proprieties cancelling eachother because that will be a nightmare to debug.