Why is the use of `!important` discouraged?

∥☆過路亽.° 提交于 2019-11-28 14:06:04

There is actual math you can use to predict, control, and reverse-engineer the impact of CSS rules. By using !important you're breaking that. Look at this JS fiddle for example, which doesn't use !important: http://jsfiddle.net/hXPk7/

If you use Firebug or Chrome dev tools to inspect the title element where it says "Richard", you should see these rules, in this order:

/**************************/
/* /hXPk7/show/ (line 20) */
/**************************/
#myExample #title .name {
    color: yellow;
}

/********************************************************/
/* /hXPk7/show/ (line 14) - Inherited fromdiv#myExample */
/********************************************************/
#myExample {
    color: blue;
}

Note that this is not the order in which they appear in the CSS stylesheet - instead they are ordered in decreasing order of their specificity. The ones which take precedence are listed first, and the others (whose rules are overridden by more specific rules) probably have a property crossed out. This demonstrates that specificity makes it easy to trace (debug?) where an element is getting its CSS properties from.

Now, compare with this JS fiddle - which is effectively the same, but has a single new rule which now uses !important: http://jsfiddle.net/hXPk7/1/

Inspect the same element using Firebug or Chrome dev tools, and you'll see something like this:

/**************************/
/* /hXPk7/1/show/ (line 20) */
/**************************/
#myExample #title .name {
    color: yellow;
}

/**************************/
/* /hXPk7/1/show/ (line 26) */
/**************************/
span {
    color: black !important;
}

/********************************************************/
/* /hXPk7/1/show/ (line 14) - Inherited fromdiv#myExample */
/********************************************************/
#myExample {
    color: blue;
}

Again, the rules are ordered according to their specificity - but note that this time, while the most specific rule which is listed first specifies a color of yellow, the browser instead renders the text as black! This is because the !important declaration has broken the normal behavior of specificity, taking precedence in a way which can be challenging to trace. Imagine a more realistic web site, with potentially hundreds of rules, and the one controlling the color isn't obvious to find, or to change.

Now, maybe this is a problem with the developer tools, but I think it reflects the fact that !important takes a normally easy-to-predict system of precedence and makes it more challenging. Maybe there are times to use it, but it should not be the first tool you reach for when writing CSS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!