When to use the !important property in CSS
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
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.
This is the real life scenario
Imagine this scenario
- You have a global CSS file that sets visual aspects of your site globally.
- You (or others) use inline styles on elements themselves which is
usuallyvery 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.