CSS 中“!important"的反义词是什么? [英] What's the opposite of '!important' in CSS?

查看:76
本文介绍了CSS 中“!important"的反义词是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 jQuery 插件,它使用 CSS 样式为嵌套的 DIV 标签添加颜色和边距.由于我更愿意将插件保存为单个文件,因此我的代码使用 jQuery 的 .css() 方法将这些颜色和边距作为 CSS 属性直接添加到 DIV.(这些属性的值可以在插件初始化时自定义.)

I'm building a jQuery plugin that uses CSS styles to add colors and margins to nested DIV tags. Since I'd rather keep the plugin as a single file, my code adds these colors and margins directly as CSS attributes to the DIVs using jQuery's .css() method. (The values for these attributes can be customized when the plugin is initialized.)

但是,我还想让用户能够使用他们自己的样式表来设置这些 DIV 的样式,因此我还向每组 DIV 添加了类(也可以为其自定义名称).这似乎是两全其美的最佳方式.

However, I also wanted to give users the power to style these DIVs using their own stylesheets, so I'm also adding classes to each group of DIVs (for which the names can also be customized). This seemed like the best way to provide the best of both worlds.

唯一的缺点似乎是内联 style="..." 属性(由 jQuery 的 .css() 方法生成)总是覆盖在外部样式表.当然,我可以在样式表中使用 !important 样式,但是一次又一次地这样做很麻烦.

The only drawback seems to be that inline style="..." attributes (generated by jQuery's .css() method) always override class styles set in the external stylesheet. I can, of course, use !important styles in the stylesheet, but doing this again and again is cumbersome.

所以:我真正想要的是一种让内联样式自动获得比外部类样式更低优先级的方法,而不必使外部类样式!important代码>.

So: what I really want is a way to make the inline styles automatically take a lower priority than the external class styles, without having to make the external class styles !important.

我没有读过这样的事情.有什么建议?(或者:我应该采用另一种方法来为插件中的 DIV 设置样式吗?)

I have not read about such a thing. Any suggestions? (Or: is there another approach I should be taking to style my DIVs in the plugin?)

推荐答案

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.

这篇关于CSS 中“!important"的反义词是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆