且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该避免在 CSS 中使用 !important 吗?

更新时间:2022-06-25 18:34:03

非常非常谨慎地使用 !important - 它几乎覆盖了所有内容,甚至是内联样式,并且在小于- 以级联"样式规则为 CSS 命名的明显方式.它很容易使用不好,并且容易成倍增加,尤其是在滥用时.您可以轻松地以想要覆盖的 !important 规则结束元素,此时您通常必须重构样式或使用另一个 !important 规则并为问题做出贡献.

Use !important very, VERY sparingly -- it overrides just about everything, even inline styles, and messes in a less-than-obvious way with the "cascade" of style rules that gives CSS its name. It's easy to use badly, and tends to multiply, particularly when misused. You can easily end up with a element with !important rules that you want to override, at which point you often have to either refactor your styles, or use another !important rule and contribute to the problem.

一旦它被传播并且你在任何地方都使用它,你就会回到没有它的情况下(很难指定足够具体的元素来覆盖其他样式),但你也不会有 !important 了,因为其他所有东西也在使用它.

And once it's spread and you're using it everywhere, you're back up in the same situation you'd be in without it (difficulty in specifying elements specifically enough to override other styles), but you also don't have !important anymore cause everything else is using it too.

当遇到 !important 看起来很吸引人的情况时——或者更糟的是,它已经在使用和传播——如果可以的话,更愿意重构你的 CSS.(坦率地说,如果你需要 !important 在用户样式表之外,通常是因为你的选择器已经太具体了,和/或你没有利用 CSS 中的 C.)你***将您的基本样式定义为尽可能接近 htmlbody 元素,并且当您想要覆盖时,尽可能少地使用特殊性和.这样,您就有足够的空间进行更改.通常,您想要覆盖样式是有原因的,这些情况通常可以归结为类名、页面的特定部分(阅读:特定的父元素)等.

When faced with a situation where !important looks appealing -- or worse, one where it's already in use and spreading -- prefer to refactor your CSS if you can. (Frankly, if you need !important outside of a user style sheet, it's usually because your selectors are already way too specific, and/or you're not taking advantage of the C in CSS.) You'd do better to define your basic styles as close as possible to the html or body elements, and when you want to override, use as little specificity as you can get away with. That way, you have plenty of room to make changes. Usually there's a reason you want to override a style, and those cases can quite often be boiled down to a class name, a particular section of the page (read: a particular parent element), etc.

(想到的唯一真正的例外是,如果您要覆盖的样式实际上超出了您的控制范围.(例如,如果您使用的框架对页面的外观有非常强烈的意见,您可能发现覆盖任何东西都非常困难.我使用过实际上插入了自己的内联样式的应用程序,只有 !important 规则可以覆盖它们.)如果您没有完全访问权限代码,覆盖和重构很容易比它们的价值更麻烦.你可以使用 !important 来收回一些控制权,只要你知道后果.)

(The only real exception that springs to mind is if the styles you're overriding are effectively out of your control. (If you use a framework that has very strong opinions on how your page should look, for example, you might find it annoyingly difficult to override anything. I've worked with applications that actually inserted their own inline styles, where nothing but an !important rule could override them.) If you don't have full access to the code, overriding and refactoring can easily be more trouble than they're worth. You can use !important to claw back some control, as long as you're aware of the consequences.)