問題描述
根據 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 類重復以增加特異性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!