CSS class repetition to increase specificity

2019-01-11 19:20发布

问题:

According to the CSS docs: 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?

For instance:

would

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

have a higher specificity than

.qtxt.lalgn
{
}

or

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

?

回答1:

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:

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

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.

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

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



回答2:

.qtxt.qtxt.qtxt would have the highest specificity...

http://jsfiddle.net/nXBTp/1/

However, this is only the case if you repeat the class name more times that any other selector, for example:

http://jsfiddle.net/nXBTp/2/



回答3:

You shouldn't need to hack specificity like this... if you need to force a value, use !important.