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:
- WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG
- (use !important rule)
- OK, now it’s working
Then the next person comes along and tries to make new changes. He tries to alter some existing CSS rules, but now their 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 class="button" href="#">Do Thing</a>
The specificity for that is 0,0,1,0
. As soon as that element has another selector affecting 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 to have a selector override the clearfix pseudo-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.
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 ;)
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.
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
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. :))
I agree wholeheartedly with this, as a developer its very important that a designer structures css properly when creating a stylesheet.
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
Your article in Smashing’s 4th Book was great! I really appreciated your advise.
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.
Wow, thanks.. I didn’t knew about this trick..
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?
As Jonathan mentioned already, I think
!important
is the right tool when it comes to create a class that is meant to override the styling of any element in the document.Also, I use
!important
whenever I style the line-height of input fields as Firefox default styles sheet contains this: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 onnth-child(odd)
instead, you’d have to explicitly reset the first clear using the same selector instead of doingAlso,
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 aclass
attribute would be the appropriate choice.I only use it when overriding ajax styles or remote styles. Usually these occur when dealing with joomla sites.
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.
Thanks for posting this educational and helpful article!
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.
Good or wrong?
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
maybe i’m not skilled enough yet… but i never used so far :)
Ahah ! Never learned how to use <code>!important</code> neither !
I am guilty to…
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.
bookmarklet – is the issue, where everything should be !important
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!
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.
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.
Odd, no mention of cross-browser min-width/height, or did I miss it somehow?
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 */
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.
in what case do the browser skip CSS commands so we need “!important” ?
thanks, good article anyway :-)
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.
This small attribute saved my life many times, especially during cross browser testing (now I’m talking about IE ;) ).
Very good this tip. I did not know this technique.
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!
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. :(
Perhaps you can send them this article =)
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.
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:
And some jquery:
Then whilst your JS is loading, you’ll get a flash of #foo being in its on-screen place. However, if we set
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
I use in two cases: for IE hacks and for print stylesheet.
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;}
!important is immensley useful for over-riding plugins, it means you can upgrade the plugin without fear!
!important is very useful like it’s name.Thanks Chris to write this article.
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.
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.
I worked on a client’s website once that had over 900 !important declarations.
Fuck me, what a pain!
I whole heartedly agree!
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 ;)
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!
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.
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;}
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
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.