#div p {
color: red !important;
}
...
#div p {
color: blue;
}
I understand how !important
works, in this case the div will ren
!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.
!important is useful when you're working with someone else's code and can't override an effect simply by using more specific selectors. When I'm asked to come in and add on a page or small set of pages to an existing site and I have to include the existing stylesheets, but can't edit them (either because of lack of access or because the trickle-down effect would break other things), that's where !important comes in handy. Otherwise you should be using selector specificity to override behavior.
don’t use the !important declaration 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.
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.
If your page includes multiple CSS files, the CSS written by you, and additional CSS that go with software written by other parties, you may want some of your CSS marked !important to "guarantee" it will not be overridden by CSS from other included files.
Also, !important
is ignored in IE6/7. So you can make use of it as an IE6/7 hack.