CSS 类重复以增加特异性

2022-01-10 00:00:00 css-selectors css css-specificity

根据 CSS 文档:http://www.w3.org/TR/CSS21/cascade.html#specificity

特异性由(除其他外)选择器中属性和伪类的数量定义.

Specificity is defined by (amongst other things) the number of attributes and pseudo-classes in the selector.

所以,我的问题是,是否可以通过一遍又一遍地重复相同的类名来增加特异性?

So, my question is, is it possible to increase specificity by repeating the same classname over and over again?

例如:

.qtxt.qtxt.qtxt.qtxt.qtxt
{
}

.qtxt.lalgn
{
}

.lalgn .qtxt//(space added to create child selector)
{
}

?

推荐答案

是的,这是可能的,也是有意的.虽然 CSS2 规范中没有提到这一点,但在 Selectors 3 规范中明确提到了这一点:

Yes, it is possible and intentionally so. While this is not mentioned in the CSS2 spec, it is explicitly mentioned in the Selectors 3 spec:

注意:允许重复出现 [sic] 相同的简单选择器,这样做会增加特异性.

Note: Repeated occurrances [sic] of the same simple selector are allowed and do increase specificity.

因此浏览器必须在遇到重复的简单选择器时增加特异性,只要选择器有效且适用.这不仅适用于重复的类,也适用于重复的 ID、属性和伪类.

Therefore browsers must increase the specificity when encountering repeated simple selectors, as long as the selector is valid and applicable. This not only applies to repeated classes, but also applies to repeated IDs, attributes and pseudo-classes.

根据您的代码,.qtxt.qtxt.qtxt.qtxt.qtxt 将具有最高的特异性.其他两个选择器同样具体;组合子根本不影响特异性计算:

Given your code, .qtxt.qtxt.qtxt.qtxt.qtxt will have the highest specificity. The other two selectors are equally specific; combinators have no bearing in specificity calculations at all:

/* 5 classes -> specificity = 0-5-0 */
.qtxt.qtxt.qtxt.qtxt.qtxt

/* 2 classes -> specificity = 0-2-0 */
.qtxt.lalgn

/* 2 classes -> specificity = 0-2-0 */
.lalgn .qtxt

另外,最后一个选择器中的空格是 descendant 组合子;child 组合子是 >.

Also, the space in your last selector is the descendant combinator; the child combinator is >.

相关文章