开发者

When to use "!important" to save the day (when working with CSS)

#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 !imp开发者_如何转开发ortant saves the day?


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:

  • Never use !important on site-wide css, or when writing a plugin/mashup.
  • Only use !important on page-specific css that overrides site-wide or foreign css (from ExtJs or YUI for example).
  • Always look for a way to use specificity before even considering !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.


Also, !important is ignored in IE6/7. So you can make use of it as an IE6/7 hack.


!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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜