CSS 类重复以增加特异性

CSS class repetition to increase specificity(CSS 类重复以增加特异性)
本文介绍了CSS 类重复以增加特异性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

根据 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 >.

这篇关于CSS 类重复以增加特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

:hover:before text-decoration none has no effects?(:hover:before text-decoration none 没有效果?)
Is CSS faster when you are specific?(当您特定时,CSS 会更快吗?)
CSS sibling selectors (select all siblings)(CSS 兄弟选择器(选择所有兄弟))
IE: nth-child() using odd/even isn#39;t working(IE:使用奇数/偶数的 nth-child() 不起作用)
How can I tell if an element is in a shadow DOM?(如何判断一个元素是否在影子 DOM 中?)
Can I use CSS to add a bullet point to any element?(我可以使用 CSS 为任何元素添加项目符号吗?)