以编程方式设置CSS选择器特异性 [英] Programmatically set CSS selector specificity

查看:132
本文介绍了以编程方式设置CSS选择器特异性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以设置CSS选择器的特异性,而不是仅由组成它的选择器的数量来确定?即,如果我有两个这样的选择器(显示计算出的特异性):

Is it possible to set the specificity of a CSS selector, as opposed to it only being determined by counts of the selector(s) comprising it? i.e., if I have two selectors like so (showing the calculated specificity):

UL OL LI        /* a=0 b=0 c=3 -> specificity =   3 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */

(示例来自 https://www.w3.org/TR/selectors/#specificity

是否有任何方法可以将第一个示例更改为此,以使两个选择器的特异性相等,而无需添加任意的类选择器:

Is there any way to change the first example to this, in order to equalize the specificity of the two selectors and without adding an arbitrary class selector to do so:

UL OL LI        /* a=0 b=1 c=3 -> specificity =   13 */

-或-

UL OL LI.red    /* a=0 b=0 c=3 -> specificity =  3 */


推荐答案

选择器的特异性是仅由其组成部分的简单选择器(和伪元素,如果有)确定。您不能在不更改选择器本身的情况下更改选择器的特异性。

The specificity of a selector is determined solely by its component simple selectors (and pseudo-element, if any). You cannot change the specificity of a selector without altering the selector itself.

如果您担心更改选择器的含义(或(可能的匹配集),您可以添加一些虚拟的简单选择器,同时保持语义不变。在您的示例中,您可以增加 UL OL LI 的特异性以匹配 UL OL LI.red 通过将不合格的:root 添加到选择器的开头(带有后代组合器)或添加:nth-​​child来对任意类名称进行依赖(n)到三个类型选择器中的任何一个一个 –两者都保证匹配,并且伪类同样特定于类选择器。

If you're worried about changing the meaning of a selector (or its set of potential matches), there are certain dummy simple selectors that you can add while keeping the semantics intact. In your example, you can increase the specificity of UL OL LI to match UL OL LI.red without actually taking a dependency on an arbitrary class name by either adding an unqualified :root to the beginning of the selector (with a descendant combinator) or adding :nth-child(n) to any one of the three type selectors — both are guaranteed matches, and pseudo-classes are equally specific to class selectors.

另请参阅以下问题的答案:

Also see my answers to the following questions for more options:

  • Can type selectors be repeated to increase specificity?
  • CSS class repetition to increase specificity

没有simi降低降低选择器特异性的一种方式,但是,既不能通过编程方式也不能通过更改选择器来实现(当然,除了通过删除多余的选择器(例如上述不合格的:root :nth-​​child(n)或重复的类型/类选择器)。

There is no similar way to decrease selector specificity, however, neither programmatically nor by altering the selector (except of course by removing redundant selectors like the aforementioned unqualified :root, :nth-child(n), or repeated type/class selectors).

这篇关于以编程方式设置CSS选择器特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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