CodeinWP CodeinWP

Everything You Need to Know About !important CSS Declarations

!important CSS DeclarationaRecently I came across a few articles that mentioned CSS !important declarations, and there was a little bit of confusion over what they actually did, and how they could be used, as expressed in the user comments on those articles.

So I thought I would research this unique CSS property/value appendage and do a comprehensive write-up on it that would go through essentially all the information developers should have before considering using !important in their style sheets.

This article will discuss what !important is, how it’s used, some practical uses for it, and drawbacks that need to be considered before implementing it.

What is !important?

!important is basically a keyword you can add to the end of a CSS property/value pair to give more weight to that CSS value. The reason it is used is due to the nature of CSS, which assigns weight to values according to where they appear in the “cascade”. A CSS style will be applied based on four factors, in this order:

  1. Direct specificity (e.g. <ul> elements are told to be 300px wide)
  2. Style importance (e.g. is the style declared in a user style sheet?)
  3. Selector specificity (e.g. <ul> elements inside of <div> elements are told to be 400px wide)
  4. Order of appearance (i.e. last one declared wins)

When the !important keyword is used on a specific property/value pair, it will cause that particular value to escape the cascade and become, as the name suggests, the most important value for that property, overriding any others.

How is it Declared?

Here is a simple example demonstrating the use of !important:

#leftSide {
  background-color: #0f0 !important;
}

#header #leftSide {
  background-color: #f00;
}

In the above example, even though the background-color style set in the second code block is more selector-specific, and is declared last, the first block will take precedence because of the addition of !important. So, the background colour of the element in question (the #leftSide element) will be green (#0f0) instead of red (#f00).

You can also have an !important declaration that overrides another !important declaration. Take a look at the following example:

div #leftSide {
  background-color: #00f !important;
}

#leftSide {
  background-color: #0f0 !important;
}

#header #leftSide {
  background-color: #f00;
}

The above styles are the same as the previous example, with the addition of another block of code at the top, which also uses !important. In this style example, the first background-color value will take precedence because of two factors: First, it uses !important; and second, it is more selector-specific.

What Are Some Practical Uses For it?

Targeting IE 5/6
One of the most well-known uses for !important is to target Internet Explorer versions 5 & 6, which ignore the !important keyword when the same property is declared within the same style block. For example:

#header {
  width: 300px !important;
  width: 400px;
}

In the above CSS, the width of #header would be 300px in all browsers except IE 5/6, which would use the second width value of 400px. Since popularity of those browsers is diminishing (but not fast enough!), the use of this “hack” is not as common anymore. Also, I personally find the * html hack to be much more practical in targeting IE6, since the addition of !important can have far-reaching, undesirable effects.

Overriding Inline Styles
A more practical use for !important is for overriding inline styles that are generated dynamically due to user-entered content. For example, a website may have a content management system that allows text formatting in a WYSIWYG interface accessible to the site owner. Since the text formatting entered in that interface must override any style sheet rules, those styles are inserted as inline styles in the generated HTML.

But those inline styles can be overridden by !important declarations in the author style sheet. Look at the following HTML code:

<div id="header" style="background-color: purple;">
<p>Praesent dapibus, neque id cursus faucibus</p>
</div>

The above code declares an inline style that makes the background-color for the #header element “purple”. This style will override any other background-color value in the author style sheet, with the exception of the following:

#header {
  background-color: #f00 !important;
}

Even with the “purple” background declared inline, the !important declaration will override the “purple” background, and instead give the #header element a background colour of red (#f00).

Editing Overridden Styles in Firebug
Another use for !important is when dynamically editing styles in Firefox’s Firebug add-on. When viewing a webpage in Firefox, you can right-click on any element and select “inspect element”, which opens the Firebug window and gives you the option to edit the page’s styles on the fly, seeing the changes in real time. Of course, these styles are only applied locally, and will reset when the page is refreshed.

A situation could arise where you need to give weight to a style listed in the Firebug window that has been overridden. Overridden styles are displayed in Firebug with a line through them. You can click on one of the overridden styles, then edit that style to add the !important keyword, and the edited style will take precedence — just as it did in the examples above.

Are There Any Drawbacks to Using It?

Absolutely. In fact, I highly recommend that !important declarations never be used. I know, that is a bold statement, and there will obviously be situations where a developer will be tempted to use it, but in 99% of cases there will be a better solution. Overriding an inline style that you can’t get to otherwise is probably the only time I would personally approve of its use. You could also use it for print-only styles. I have been coding HTML and CSS for about 9 years now, and I have never used an !important declaration. In fact, for a long time I never even knew it existed, which, in retrospect, was a good thing.

Some of its drawbacks include:

  1. Encourages sloppy, poorly thought-out code
  2. Creates code that is less maintainable
  3. Overrides styles declared in user style sheets, thus degrading accessibility

With those significant factors in mind, use of !important should be considered only after all other avenues have been exhausted.

Additional Technical Facts

When the !important keyword is used, it must follow the value of the property that it intends to give weight to.

The !important keyword can be used in conjunction with CSS shorthand. When used in this way, !important will give weight to each of the values declared in the shorthand code. For example:

#header {
  padding: 20px 10px 20px 10px !important;
}

div#header {
  padding-left: 0;
  padding-right: 0;
  padding-top: 0;
  padding-bottom: 0;
}

With the above CSS, the first code block, which declares the padding in CSS shorthand, will take precedence over the second block — even though the second block is more selector-specific, declares the padding in longhand, and is declared last in the cascade.

An !important declaration that is defined in a user style sheet will have more weight than one defined in an author style sheet (although it was reversed in CSS1). This is true even though an author style sheet will take precedence over a user style sheet in the normal flow of the cascade.

The primary purpose of the !important keyword is to allow users with special needs to include it in their own user-defined style sheet, in order to affect font size and font color settings without those styles having to obey the natural cascade.

Finally, there have been, surprisingly, a few articles that have stated that the following method is the only way to override inline styles:

div[style]{
  background-color: #f00 !important;
}

Take note of the [style] declaration, which is an attribute selector, in addition to the !important keyword. In this example, we’re accessing all <div> elements that have an attribute of “style” set in the HTML. This is not needed. The !important keyword is all that is required in order to override inline styles in the example above. However, using the attribute selector specifically targets elements that have the “style” attribute set, so there could be practical uses for it.

Of note is that attribute selectors don’t work in IE6 and IE7, so this method becomes even less useful if you have to support those older browsers.

Update (June 2/2009): After thinking about this, I realized I overlooked an important factor here: Since inline styles can be added to numerous HTML tags that don’t have classes or IDs, and we never know which tags will have the styles added, using the attribute selector would be the only way to override those styles, so I can see why those articles were so adamant about this being the only method to override inline styles. However, I think a more thorough explanation would have made it more clear. I suppose you could also use JavaScript to target all tags with inline styles and write a class to them.

In Conclusion

In conclusion, don’t use !important declarations unless you’ve tried everything else first, and keep in mind any drawbacks. If you do use it, it would probably make sense, if possible, to put a comment in your CSS next to any styles that are being overridden, to ensure better code maintainability.

I tried to cover everything significant in relation to use of the !important declaration, so please offer comments if you think there’s anything I’ve missed, or if I’ve misstated anything, and I’ll be happy to make any needed corrections.

32 Responses

  1. Josh L says:

    Fantastic writeup for a subject that hasn’t been organized into one place.

    It’s already on the front page of Google for “css important declaration” and will be on the front page for simply “css important” very soon with all the links you’ll get, which is great news for the people who will be searching for this info.

  2. Mario says:

    Very Good. Loved it. Good Explanation

  3. Andy Walpole says:

    I occasionally use it when designing a site – but I know it’s something I’ll need to remove later on.

    If you find yourself having to use !important for a style declaration then you know there’s something wrong with your CSS code elsewhere that needs correcting.

  4. Ray Gulick says:

    Best, most thorough explanation of !important declaration I’ve ever seen. Thanks for researching and posting this.

  5. Steven Hart says:

    I kinda disagree.

    True, it’s not such a great idea to use !important as you have said. But there are a lot of occasions when I’ve had to use it to save time on editing someone elses poorly written CSS.

    What else am I supposed to do when given a mountain of changes to be done in just a couple of hours? It’s unrealistic to have to trawl though thousands of lines of code just to change one small statement.

    Lets also not forget that it validates. Sorry, but in my opinion the pros outweigh the cons.

  6. @Steven, you’re absolutely right. Instances like that would warrant the use of !important. Like I said: 99% of the time.

  7. Juhi says:

    I had seen it in a couple of places and didn’t know what it did. At first thought it sounds like such a useful thing. But you have made some good arguments against its use.
    Thanks for the explanation,
    Juhi

  8. JLsubdesign says:

    The !important declaration is my best friend when it’s time to use TELERIK and his inline style code !

  9. Michael says:

    How do you feel about using it to force a scroll bar to appear on short pages in firefox? Centered content appears to jump from short pages to long pages.

    CSS to apply:

    html{overflow:-moz-scrollbars-vertical !important;}

  10. Jarek says:

    I’m using !important only to fix styles in IE6. When something is wrong I’m creating ie6.css and put in it code that overrides some styles.

  11. John F says:

    Thank you for this explanation.

    I use a lot of ProjectSeven products which make a lot of use of ‘!important’ in their css. Al Sparber and Gerry Jacobsen of PVII seem to be highly regarded CSS exponents and I would have thought that they would have deployed the purest and leanest coding for their products.

    I wonder why they make so much use of it?

  12. red says:

    On place I’ve found !important declarations to be very useful and not requiring apologies (which I rarely give for any of my coding decisions anyway) is in their application in alternate print stylesheets (using ‘media=print’) in this case, cascading logic needs to be overridden for a specific rendering. It would be a wasteful and often impossible exercise to distort the flow of logic and inheritance simply to accommodate a variant output for page printing. The !important declaration makes it far easier to override well-formed structure, momentarily and for this purpose, leaving otherwise well-structured styling intact for the main application of presenting web pages online. I find nothing in comments here or elsewhere that would argue against such usage.

  13. Kim H says:

    In my five years of coding, I’d say that I’ve probably only *seen* it used one time; it was to create an IE hack. I edited it out, and the page worked fine in IE6 after adding in an HTML conditional in the actual mark-up that was affected. Now, perhaps adding in the conditional was probably not the best choice, but I preferred that method over doing a hack; after all, hacks are, generally speaking, not quite *standards* and (at least I feel) makes the code feel sloppy. I definitely agree that the !important property statement shows that the code isn’t very well constructed; I try to design my stylesheets to at least somewhat mirror my markup; body elements appear at the top, navigation elements below there, body elements in order below that, et cetera, so that I can easily find where I’ve declared a class in order to edit its properties in a more efficient manner.

    Besides, if we are using this to override code, why don’t we go back and edit the original code instead? It’ll at least cut down on file size somewhat :)

  14. Dominica says:

    this was the best thorough explanation of the !important property for css I’ve seen yet, well written and well displayed.

    Thanks brother

  15. Timothy says:

    This all seems very !important…

  16. jmr says:

    Really useful stuff here, I’ve never really understood why important was used in CSS. I knew it was to mark something as not being able to be overwritten, but this makes a whole lot more sense now!

  17. parag says:

    I have img alt=”” style=”width: 700px !important; height: 650px

    !important” src=”http://image/testimg.jpg” />. But if I set height to

    400px and width to 350px dynamically using javascript, the IE 7 & 8

    takes the dynamicaly set values using javascript. whereas in firefox,

    it takes width to 700px and height to 650px; how IE is making

    problem??
    Thanks in advance for any replies

  18. Alon says:

    Very usefull with you need overwrite some script that creats css code.

  19. What if you are sharing some html/css code with other sites and, no matter what, you don’t want the other site’s css to override the rules of your markup? Isn’t the use of !important valid then?

  20. And here’s why you don’t use ID-s for styling purposes: http://codepen.io/chriscoyier/pen/lzjqh That also puts too much weight to selectors and that will cause problems later.

  21. Toby Osbourn says:

    Great post summing up why !important probably isn’t the best solution in the world most of the time. I think too many people see it as the easy way out.

    There is another (fairly new) use-case for why !important can ruin your day that I have blogged about, basically it is that Firefox will honour !important properties to the point of not animating them.

    http://tosbourn.com/2013/03/development/firefox-honours-important-in-css-animations-no-one-else-seems-to/

    • Hey, Toby. Thanks for providing that test. That’s actually an interesting difference in how the browsers treat that.

      It would seem that the correct behaviour should be to ignore the animation because the !important declaration should take precedence over the non-important one in the animation.

      However, it would seem that in Firefox, if you add !important to the animated rules, that should change it to now animate:

      http://jsbin.com/ohufah/1/edit

      But not only does the 2nd box not animate, but now the first box stops animating in Firefox (same effect in Chrome). So I’m thoroughly confused. :)

      I’m not sure how these are supposed to be handled, but I think I might submit a bug report for both Chrome and Firefox, because they really should handle these the same way.

      Oh and as a side point, in your example, you had incorrectly written !important with a space between the exclamation point and the word “important”, but that didn’t seem to have any effect on the outcome, so it seems to be the same even when that’s fixed.

    • Just to make sure this is handled and corrected cross-browser in a consistent way, I’ve filed a bug report for both Chrome and Firefox to see what the devs over there say:

      https://code.google.com/p/chromium/issues/detail?id=223450
      https://bugzilla.mozilla.org/show_bug.cgi?id=854242

      Thanks, Toby. Nice find!

  22. Kuroneko says:

    If you are coding both the front-end and the back-end then there are times you’ll have to use !important. It saves time. But if you are only coding the front-end part then it’ll be a shame if you declaring !important everywhere.

    • I understand that. In fact, for a quick fix, especially on a deadline and when a client is breathing down your neck, sometimes it’s the only choice.

      But if you find yourself using !important regularly, even when you’re not under pressure, then you’re overusing it and later when you go back to that code, it will cause problems. It’s much more difficult to maintain a stylesheet when it’s overloaded with !important declarations. And this isn’t just my opinion, it’s the collective opinion of many well respected developers and authors nowadays.

  23. sucharita ghosh says:

    thank you

  24. Nate Balcom says:

    I’ve found it useful for print styles. The site I’m working on right now is loaded with !important classes. I didn’t put them there, but I am working with them. It’s helpful for using with my print.css. When it loads print.css it’s become helpful for stripping elements out of the page.

  25. Zahid Hasan says:

    Why not use two separate class instead of using !important?

    I am just confused as to why I would need to override?

    For example:

    TESTING THIS OUT
    TESTING THIS OUT ALSO

    .notImp {
    width: 100% !important;
    height: 100px;
    background: #FF0000;
    }
    .notImp {
    width: 20px;
    height: 100px;
    background: #00FF00 !important;
    }

    Both DIVs have green background and at 100% width… so why couldn’t I just use:

    .notImp {
    width: 100%
    height: 100px;
    background: #00FF00;
    }

    • That’s not a situation where you would use it. Most people use it when the style they are trying to override has too much specificity. It’s hard to explain, but you’ll have to do some research on CSS specificity in order to grasp why !important is sometimes used.

  26. Thanks for the tipo
    The !important flag has solved me a lot of troubles

  27. George Rosar says:

    This is extremely important when doing css3 transitions kids!

  28. sanjay saharan says:

    nice article.
    i like it.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).