且构网

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

CSS 中“!important"的反义词是什么?

更新时间:2023-11-10 11:12:40

CSS 中 !important 的反面是什么?

没有完全相反的选择器,但有较低优先级的选择器.

There isn't an exact opposite, but there are lower precedence selectors.

w3c 规范定义了级联,不妨阅读它.

内联样式具有最高优先级,而您要使用低优先级样式,则需要通过样式表或 style 元素添加 CSS.

inline styles have highest precedence, and you're after a low-precedence style, you'll need to add CSS via a stylesheet or style element.

因为您使用的是 jQuery,所以添加自定义样式元素非常简单:

Because you're using jQuery, adding a custom style element is very easy:

$('<style type="text/css">.foo {color: #FF0000;}</style>').prependTo('head');

然后您将发现的问题是,在样式表中指定了 .foo 的用户需要更高的特异性才能胜过 style 元素,所以我建议为每个元素使用一个额外的类,以便用户可以覆盖默认值:

The issue you're then going to find is that a user who has specified .foo in a stylesheet will need a higher specificity to win out over the style element, so I'd recommend using an additional class for each element so that a user can override the defaults:

.foo.override { color: #0000FF; }

在所有情况下,您都需要仔细选择选择器,以尽可能降低特异性.

In all cases you're going to want to carefully pick your selectors to have the least specificity possible.