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 类重复以增加特异性


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01