Grow your CSS skills. Land your dream job.

When Using !important is The Right Choice

Published by Chris Coyier

Inspiration from Stephanie Rewis:

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:

  1. WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG
  2. (use !important rule)
  3. 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:

.button {
   background: red; 
   color: white;
   padding: 3px;
   border-radius: 5px;
   border: 1px solid black;
}
<a href="#" class="button">Do Thing</a>

The specificity for that is 0,0,1,0. As soon as that element has another selector effecting it that has a higher specificity, you may have styling issues. Like:

<section id="content">
   <p>  text text blah <a href="#" class="button">Do Thing</a>  </p>
</section>
#content a {
   border-bottom: 1px dotted blue;
}

Now those buttons you have a specific design for have a dotted blue bottom border, which is not what you want. Here's a fiddle of that kinda scenario happening.

I don't think this is the fault of sloppy CSS. It's easy and often perfectly valid to write a CSS selector that has a higher specificity value than 0,0,1,0 and accidentally screws up a button.

To make your button class super robust and not easily trifled with, put !important rules on the values. And maybe even add in a few that your button doesn't need but could screw it up.

.button {
   background: red            !important;
   color: white               !important;
   padding: 3px               !important;
   border-radius: 5px         !important;
   border: 1px solid black    !important;

   /* For good measure */     
   text-decoration: none      !important;
}

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.

Comments

  1. 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 ;)

  2. I tend to use !important when dealing with rules set by javascript-generated inline html. much easier than going through long JS files to find said code.

    Also use it for cases like the .button mentioned.

  3. 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 */
    }
  4. Matt edwards

    I use it sparingly but I would be interested to know if I am using iy correctly with in wordpress.

    I use it when a plugin styling is over riding my CSS (and the plugin CSS is quite specific) my thought process is that altering it in my CSS will save it being removed when the plugin is updated.

    Is there a better way to do this?

  5. 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.

  6. 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

    .foo li {
        clear: none !important;
    }
    .foo li:nth-child(odd) {
        clear: left !important;
    }

    Also, img { max-width: 100% !important; } is often useful in mobile stylesheets.

    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.

  7. Umber

    I only use it when overriding ajax styles or remote styles. Usually these occur when dealing with joomla sites.

  8. 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.

  9. Miles

    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.

    Thanks for posting this educational and helpful article!

  10. Patrik

    I have a few times added the body tag to the button class when I have a special styling for the links in the entry.

    .entry a {text-decoration: underline}
    body .button {text-decoration: none }

    Good or wrong?

  11. an advice for good programming practice:

    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

  12. Peter

    maybe i’m not skilled enough yet… but i never used so far :)

  13. 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.

  14. seelts

    bookmarklet – is the issue, where everything should be !important

  15. 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.

    Bagoosh!

  16. Jared

    When trying to do anything in SharePoint !important is a must.

    • 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.

    • sher

      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.

  17. seutje

    Odd, no mention of cross-browser min-width/height, or did I miss it somehow?

    #foo {
      width: auto !important;
      width: 200px;
      min-width: 200px;
    }
    • The only “major” browser right now that doesn’t support min-/max-width is IE6. I’d rather target it specifically:

      min-width: 200px;
      _width: 200px; /* IE6 only */

  18. Luke

    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.

  19. in what case do the browser skip CSS commands so we need “!important” ?

    thanks, good article anyway :-)

  20. 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.

  21. This small attribute saved my life many times, especially during cross browser testing (now I’m talking about IE ;) ).

  22. Very good this tip. I did not know this technique.

  23. Anthony

    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 : )

    Thanks folks, and another great article Chris!

  24. Andres Botero

    I can´t use !important , the “Quality Assurance” department at my work won’t let me use it. They say it’s not a good practice. :(

  25. I used !Important in my wordpress child theme to override the parents style (I only needed a few modifications, so it was OK to do this in my eyes)

    • Child themes load their CSS after the parent theme, so as long as you use the exact same selector as the parent, you don’t need !important rules to override. Careful with that.

  26. 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.

    TTFN,

    Aaron

    • That last bit should’ve read:

      “Then do a

      <noscript>
      <style type="text/css">
      #foo {
      left: 0px !important;
      }
      </style>
      </noscript>

      :oE

  27. Some guy

    I use in two cases: for IE hacks and for print stylesheet.

  28. Austin Williams

    I have been putting an id on the html element

    <!doctype html><html lang=en id=I>
    ...

    Or if you want to get really creative you can use the ! as an id.

    <!doctype html><html lang=en id=!>
    ...

    Then in your css you can bump the power of any css selector like so.
    .content .class{background:pink}
    #I .class{background:orange;}

    If you use the ! point, you have to escape it

    .content .class{background:pink}
    #\! .class{background:orange;}

  29. !important is immensley useful for over-riding plugins, it means you can upgrade the plugin without fear!

  30. !important is very useful like it’s name.Thanks Chris to write this article.

  31. First of all thanks Chris for writing this article..

    I honestly am trying to avoid the usage of !important when writing css. In your example, instead of using !important, I would rather use:


    #content a.button, .button {
    background: red;
    color: white;
    padding: 3px;
    border-radius: 5px;
    border: 1px solid black;
    }

    But !important becomes handy when using it as a css hack for IE max-height bug-fix. As you might know, IE doesn’t recognize max-height (max-width), therefore you can do the following:


    #wrapper{
    max-width: 500px; /* for most browsers excepting IE */
    width:auto!important; /* IE max-width hack */
    width:500px; /* width value must be the same as max-width value */
    }

    This will help you to have a max-width or max-height in IE7+. Maybe it is working in previous versions of IE, but I didn’t tried it.

  32. I haven’t been reading all the comments, but I (think) I sometimes need it to overrule the style rules certain WordPress plugins use. I do think it’s a life saver at those times.

  33. I worked on a client’s website once that had over 900 !important declarations.
    Fuck me, what a pain!

  34. Rob Huzzey
    Permalink to comment#

    The !important rule is so widely used incorrectly it has become a bad word.

    Personally I don’t like to use it at all, mainly because when I code I try to think about the other DEV who will have to work on the CSS later.

    When I come across it, I tend to look at why it’s been done, often it’s perfectly valid, other times it’s simply a ‘quick fix’ that never should have gone out.

    My view is this, use it only when you have no other choice, with great power comes great responsibility ;)

  35. Permalink to comment#

    I had something witty to say about the post but forgot after reading the comments.

    Good stuff as usual. Keep on keeping on and whatnot!

  36. 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.

  37. Dan
    Permalink to comment#

    I used !important for a situation where you have something like :

    .stylized .stylized_table tr:nth-child(even){background-color:blue;}

    and you want to highlight that table row by setting a class ( because your cool like that ).

    So then my highlight class would be something like :

    .highlighted{background-color:red !important;}

  38. Damon
    Permalink to comment#

    I think most uses of !important are pretty problematic. Even if it seems fine now..

    One place I think they make sense is places like

    .hide {display: none !important; }
    

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".