#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. Does anybody know any 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!
important flag are applied to the same element, the declaration with a greater specificity is applied. Using ! important to override specificity is considered a bad practice and should be avoided for this purpose.
To avoid using ! important , all you need to do is increase specificity. In your case, both of your selectors have identical specificity. The issue is most likely caused by your media query being placed before your "Normal CSS", and thus getting overridden.
To override the CSS properties of a class using another class, we can use the ! important directive. In CSS, ! important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.
Consider this:
#someElement p {
color: blue;
}
p.awesome {
color: red;
}
How do you make awesome
paragraphs always turn red, even ones inside #someElement
? Without !important
, the first rule will have more specificity and will win over the second rule.
Only as a last resort! This is because once used it is hard to override it. My rules of thumb:
!important
on site-wide css, or when writing a plugin/mashup.!important
on page-specific css that overrides site-wide or foreign css (from ExtJs or YUI for example).!important
.!important
saves the day in cases where you dont control HTML output and it renders a style=''
attribute. Think ASP.NET and other frameworks.
The only way you can then change this styling is by either using javascript or marking your CSS rule as more !important.
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