What does !important mean in CSS?

后端 未结 5 1336
后悔当初
后悔当初 2020-11-21 23:32

What does !important mean in CSS?

Is it available in CSS 2? CSS 3?

Where is it supported? All modern browsers?

5条回答
  •  梦毁少年i
    2020-11-22 00:06

    It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'

    In normal use a rule defined in an external stylesheet is overruled by a style defined in the head of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important 'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.

    Also, ordinarily, a more specific rule will override a less-specific rule. So:

    a {
        /* css */
    }
    

    Is normally overruled by:

    body div #elementID ul li a {
        /* css */
    }
    

    As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.

    If, however, you add !important to the less-specific selector's CSS declaration, it will have priority.

    Using !important has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.

    It also makes debugging your CSS a nightmare (from personal, empirical, experience).

提交回复
热议问题