CSS class repetition to increase specificity(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 类重复以增加特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CSS 类重复以增加特异性


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01