When Using !important is The Right Choice

Share this:

Using !important in your CSS usually means you're narcissistic & selfish or lazy. Respect the devs to come...

For those that don't know, an !important rule works like this:

p {
color: red !important;
}
#thing {
color: green;
}

<p id="thing">Will be RED.</p>

The paragraph is will be red, even though the ID selector has higher specificity. The !important rule overrides that particular property.

Stephanie, surely out of frustration, was talking about how postscripting your CSS values with !important can be highly abused and make for messy and hard to maintain CSS. The unfortunate typical use case goes like this:

WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG

(use !important rule)

OK, now it's working

Then the next guy comes along and tries to make new changes. He tries to alter some existing CSS rules, but now his changes aren't behaving how they should. He traces the issue back to the !important rules, then has a choice. He can try and remove those and attempt to get things back on track, or add some more of his own to fight them and get his change done. Since he might not know exactly why those !important rules were added in the first place, he might opt for the second option for fear of breaking something somewhere else on the site he's not aware of. And thus the vicious cycle starts.

Potentially good use case: utility classes

So when is the !important rule actually useful and a good idea? In my opinion, utility classes are a good use case.

Think of "buttons." Let's say you have a class name of .button on your site and whatever element you put it on, you want that element to look like a button: specific font, rounded corners, special background and borders, whatever. So you do this:

Any other "utility class" could benefit from this. Think of the popular "clearfix" class, which uses pseudo elements to do its thing. Pseudo elements are becoming more popular and being used for more things, so it would be possible have a selector override the clearfix psuedo elements and have the float clearing fail. Almost certainly not what you want, so adding !important rules to those could be useful.

I even talked to Nicole Sullivan who said she'd be adding !important rules to the spacer classes that she uses in her OOCSS framework, and she's a hard sell on this idea, since her style of writing CSS actually makes writing selectors with a higher specificity than 0,0,1,0 kind of rare.

User style sheets

I believe the original use case and reason !important rules exist is user stylesheets. That is, a custom stylesheet written by you that you tell the web browser to apply to every page visited. This is particularly easy to do in a browser like Safari. Preferences > Advanced > Stylesheet and select one. In this user stylesheet, you might do things like hide comments, hide ads, or attempt your own readability improvements by settings colors and sizes on fonts.

Since these styles apply to all websites, not specific websites, you'll need to write fairly generic selectors that are the most likely to apply to all sites, like body { }. But a selector like that has very low specificity (0,0,0,1) and is likely to be beaten by a websites own styles. And so, !important rules allow you write generic selectors but still have the power to change things.

Others?

So what about you folks? Got some use cases for !important you think are solid? I'd be interested to hear.

Share this:

Comments

I’ve got a use case in my CMS where I use TinyMCE to allow editing of HTML. Íf the user has a stylesheet specific for TinyMCE hosted on their website, the editor loads it, but often things like the background color won’t become visible the way they should, because TinyMCE itself has set a few !important rules of it’s own. By adding !important once more, I’m able to let my clients edit in the style of their page/article, the way they’re used to. I was able to find this problem rather quickly thanks to the web inspector. You really made me love that inspector, Chris ;)

for print stylesheets especially when you are building a Multi -language website, cause most of the time you will be targeting other languages like this

body{
background:green;
}
html[lang="ar"] body{
background:red;
}

when you are writing a print stylesheet the second rule will always override cause of higher specificity & sometimes the cascade too (it depends on how will you organize your stylesheet). so to override this you will need !important declarations instead of writing 2 rules one for each language.

I’ve got some thoughts on CSS architecture but I’ve yet to write them up, so I’ll have to explain them quickly here:

The example you’ve shown with button demonstrates why you shouldn’t use !important. You’ve now made it more difficult to subclass your button. The problem in this case is the “#content a” declaration as it’s the one that messes things up and should be avoided. You’ve used a very specific ID selector to target a very generic link element in a part of the page that is very broad: your content. Broad styles like this should be specified as page level styles, ie: “a { … }”, and then more targetted for a certain class of elements.

For example, on this very site, there are boxes in the sidebar that have links. Again, the inclination might be to do something like “#sidebar a { … }” but again, that’s too specific for a generalized area. Those links exist within specific modules which use classes (.sidebar-box, in this case). Links in those containers can then be styled differently from the rest of the page using “.sidebar-box a { … }”.

What about buttons that might appear in a sidebar-box? Then, the style could be targetted using “.sidebar-box .button” which has a greater specificity without the need for !important.

With that said, I do believe there are times when using !important is valid: generalized states. Objects on our page may be in a particular state like ‘hidden’ or ‘error’ that are meant to override the default state and style of the object. A generalized state is a class that could be applied to any element anywhere on the page. As a result, it needs to bulldoze through specificity and that’s where !important comes in.

(And with that, I shall work to document my thoughts in more detail so that all of this makes a little more sense. :))

agreed…
when i am developing and find a case where i just want to use !important and be done with it, i try to experiment to see how i can rewrite my selectors to avoid the need for !important – usually end up with better written css at the end

I used it on a special ocasion for making IE9 keep the overflow as the normal browsers. In the case, on ie<9 it showed up a message telling the user to upgrade the browser, so in all the other browsers the contet would overflow normaly, but IE9 still understand some buged css, so i had to use !important to it render correctly.

body {
overflow:auto !important; /* for all other browsers, the !important is for IE9 */
overflow:hidden\9; /* for IE<9 */
}

I’ve found myself overriding inline styles, which are also usually a bad practice. But, images on my site float from inline styles rather than classes, which facilitates text flow in RSS feeds, etc.

In a mobile stylesheet right floats are a usability concern since they can interrupt finger-scrolling and push out the layout. !important is a big help in this instance because the inline styles trump everything in the cascade.

When using media queries, it’s sometimes necessary or at least acceptable to override styles using !important. Say you clear something with .foo li:nth-child(4n+1) { clear: left; } in your main stylesheet, and then want to clear on nth-child(odd) instead, you’d have to explicitly reset the first clear using the same selector instead of doing

Off topic:
What is your reasoning behind using rel="CSS" in your code examples? The HTML spec has the example <pre><code class="language-pascal"> which suggests that a class attribute would be the appropriate choice.

The only occasion I have ever found myself using important rules was to override styles of external javascript I had no possibility of editing myself. Other than that I think css provides enough possibilites to style a page without the need to rely on important rules.

Yes, this very often happens to me. As I learn more and more and become more and more advanced in the art(s) of HTML and CSS, I begin having to use the !important style less and less in my CSS, which I agree, is a very good thing. I’m still struggling just a bit to completely understand specificity, although it hasn’t been too much of a problem so far.

every time you use !important, write a short comment for generations to come – like: ‘makes shure all buttons are the same’ or ‘override for JS set styling for … ‘ – making it clear, why !important is there

note to myself: i dont comment !important yet, but i ‘m starting to comment my css more and more, so comments on !important will be included in future work

I’ve found it can be useful when dealing with 3rd party integration where their front-end code looks like (and probably was) written by back-end guys 10-years ago. It can also be handy with overriding styles of 3rd party JavaScript.

Where I work (enterprise land), we recently outsourced the back-end integration of a SharePoint 2010 project to India and when I was reviewing a milestone, they had littered the global css with !important. You’re seeing it and thinking “Holy. Shit.” Then you’re thanking God the vendor is taking on the technical debt. It’s amazing to me, the worst shit I’ve seen in my career has been at this job – and it’s 2011.

I actually wrote a post touching on this topic a bit, “Rules that every theme developer should abide by”.

I think using !important is the lazy way out. You really don’t need it unless you want to override some tags and if your developing something, you shouldn’t need to override your own tags.

You should use it if your styling a third party theme that has default style sheets for it’s core. LightCMS for example has it’s own Core style sheets that sometimes mess up your look, so you need to override them with !important.

Same goes with the Gantry framework and I’m sure a few other things as well.

Not really, you can override default SP styles and when you inspect elements you can tell where rules are coming from in the cascade. Our India crew went nuts with !important because they don’t understand the cascade, nor good front-end development.

I more than agree with Jared here. SP2010 has an enormous amount of inline styling, which is produced from uneditable default server-side scripts. Important tags are a must for any SP site that is not a completely custom build.

Even so, even the sloppiest CSS is looks beautiful when compared to the Spaghetti Factory of mark-up SP2010 spits out. By virtue of deciding to use SP, we take is with a grain of salt and move on.

I personally use it when i’m dealing with some 3rd party widgets where I dont exactly have full control on the outcome . An example is one of the twitter feed widgets. Usually you get some control by declaring it in the javascript, however I prefer to leave it how it is and style it myself. I also get much more control over the final outcome this way also.

Only other time I have really used !important is back in the day when I would create a template for something like myspace but that was years ago.

I use !important very sparingly. I use it for print media (remove floats / make 100% width, etc) and sometimes to override “plug and play” CMS plugins’ inline styles that would be a pain to maintain/edit (since I am not the author of the files). In the latter, I figure that it would more tedious for someone in the future to edit the plugin CSS than to edit my CSS with an !important next to it.

Sadly, I think I probably fall under the category “doesn’t know any better” rather than “lazy”.

I’d actually never used the !important declaration until a couple of weeks ago while working on my new website. I sat here for hours trying to get the background of an text input field to be transparent in IE 7 and it just wouldn’t play ball. As usual everything worked great in all other non-IE browsers!

Having tried everything I could think of and googling around for ages I eventually remembered something about “!important”, tried it and it worked.

I have to say, after the frustrating hours of having NO idea why my background styles weren’t working this felt like a gift from above.

If there is a better way to achieve this without using !important I’d be very grateful if someone could enlighten me : )

I like !important for noscript stuff. Say you’ve got a whole bunch of opacity and positional stuff going on in jQuery, and you want your site to be browsable without it, whack a loada !important css in some noscript and hey presto…

Why wouldn’t you just set default CSS and then manipulate it with jquery? Well consider this:

#foo {
position: absolute;
}

And some jquery:

$('#foo').css('left','-200px').animate({left: '+=200px');

Then whilst your JS is loading, you’ll get a flash of #foo being in its on-screen place. However, if we set

#foo {
position: absolute;
left: -200px;}

In our css and then do a

#foo {
left: 0px !important;
}

Then people without JS enabled will definitely see #foo in its final animated position.

I work at a place right now that uses “!important” everywhere in conjunction with other folders full of files for overriding other styles. It’s a nightmare to work on these pages. It’s causing a lot of the issues I’m experiencing. Just awful.

1) When you’re overriding javascript set inline styles for a media queries, print style sheets and so on.
2) When you’re overriding the use of !important in a third party style sheet (cough bootstrap cough).
3) When you’re fixing some weird browser bug that for some reason you can only fix using !important
4) When you just feel like being a dick.

In no other circumstances, IMO, should it be used, and you should always leave a comment saying why you used it so that future developers can figure out what will break if they take it out.

This comment thread is closed. If you have important information to share, please contact us.

Related

How do you stay up to date in this fast⁠-⁠moving industry?

A good start is to sign up for our weekly hand-written newsletter. We bring you the best articles and ideas from around the web, and what we think about them.

👋

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress and powered up by Jetpack. It is made possible through sponsorships from products and services we like.