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

前端 未结 7 1839
北海茫月
北海茫月 2020-12-04 02:10
#div p {
    color: red !important;
}
...
#div p {
    color: blue;
}

I understand how !important works, in this case the div will ren

相关标签:
7条回答
  • 2020-12-04 02:11

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

    0 讨论(0)
  • 2020-12-04 02:20

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

    0 讨论(0)
  • 2020-12-04 02:25

    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 讨论(0)
  • 2020-12-04 02:28

    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.

    0 讨论(0)
  • 2020-12-04 02:30

    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.

    0 讨论(0)
  • 2020-12-04 02:31

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

    0 讨论(0)
提交回复
热议问题