When to use the !important property in CSS [duplicate]

Solution 1:

This is the real life scenario

Imagine this scenario

  1. You have a global CSS file that sets visual aspects of your site globally.
  2. You (or others) use inline styles on elements themselves which is usually very bad practice.

In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.

Actual real world example?

This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.

Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...

I suppose you got the idea by now and can come up with some others as well.

When do you decide to use !important?

I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.

Solution 2:

Overwriting the Style Attribute

Say in the example that you are unable to change the HTML source code but only provide a stylesheet. Some thoughtless person has slapped on a style directly on the element (boo!)

       div { background-color: green !important }
    <div style="background-color:red">
    <p>Take that!</p>
    </div>

Here, !important can override inline CSS.

Solution 3:

This is a real, real life scenario, because it actually happened yesterday:

  • Z-index in jQuery dialog. Autosuggest list not displayed properly

Alternatives to not using !important in my answer included:

  • Hunting down in JavaScript/CSS where a certain elusive property was being applied.
  • Adding the property with JavaScript, which is little better than using !important.

So, a benefit of !important is that it sometimes saves time. If you use it very sparingly like this, it can be a useful tool.

If you're using it just because you don't understand how specificity works, you're doing it wrong.


Another use for !important is when you're writing some kind of external widget type thing, and you want to be sure that your styles will be the ones applied, see:

  • Appended control's CSS

Solution 4:

You generally use !important when you've run out of other ways to increase the specificity of a CSS selector.

So once another CSS rule has already dabbled with Ids, inheritance paths and class names, when you need to override that rule then you need to use 'important'.

Solution 5:

I have to use !important when I need to overwrite the style of an HTML generated by some JavaScript "plugin" (like advertising, banners, and stuff) that uses the "style" attribute.

So I guess that you can use it when you don't control the CSS.