CSS: In defense of !important

!important isn’t bad and you shouldn’t feel bad — if you know how to use it

What’s wrong with !important

div {
background-color: blue;
font-size: 2em;
}
div.some-item-whatever {
background-color: red;
}
div#item {
background-color: green;
font-size: 3em;
}
div {
background-color: blue !important;
font-size: 2em;
}
<div id="item">¯\_(ツ)_/¯</div>

Weren’t you supposed to defend !important?

.hidden {
display: none !important;
}
  • Overriding 3rd party code.
  • Different media (for instance, if you need to set unique attributes for the print version of your page).

TL;DR version

  • !important is bad if you use it reactively — this means you should avoid breaking specificity rules and cascading because you want to trump yourself.
  • If you use !important out of laziness, you are not taking into account the implications of your actions. It will grow, you (and your team) will end up abusing it, and you are going to end up with a messy, unmaintainable code and ranting on Twitter.
  • !important is OK when used proactively. It’s an outstanding way to achieve immutability in CSS.
  • It comes in hand with an utility-first approach, where utility classes should do one thing and do it well (SRP).
  • And, well, !important is the only way to trump inline styles. So if you are using some third-party code that provides inline styles (why would you?)… then this is the only way to go.

--

--

Words matter – Software product development, Front-end, UX, design, lean, agile and everything in between. https://afontcu.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrià Fontcuberta

Words matter – Software product development, Front-end, UX, design, lean, agile and everything in between. https://afontcu.dev