Consider:
#div p { color: red !important; } ... #div p { color: blue; }
I understand how !important
works. In this case the div will render red because now it has priority (!important
). But I can't still figure out an appropriate situation to use it in. Is there an example where !important
saves the day?
The ! important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the ! important rule, it will override ALL previous styling rules for that specific property on that element!
The ! important statement is used for breaking this order and adding weight to a specific declaration to put it in effect, ignoring the others. It is used for overriding the styles that are previously declared in other style sources, in order to achieve a certain design or layout goal.
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'.
important rule in CSS gives you the ability to override styles, but is this power too much for a lone software developer? Read this article to find out what it is, and when it's a good idea to use it! The ! important rule is special because it has the ability to override the natural cascade of CSS styles.
Imagine this scenario
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
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.
!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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With