哪个CSS选择器更强? [英] Which CSS selector is stronger?
本文介绍了哪个CSS选择器更强?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
哪个选择器更强?
#nav li.current
pre>
或
div #nav li
和第二个
a.test
或
.test .test
答案是什么?
解决方案
选择器的特异性计算如下:
- 计数选择器中的ID选择器数量(= a)
- 计算选择器中的类选择器,属性选择器和伪类的数量(= b)
- 计数选择器中的类型选择器和伪元素数量(= c)
- 忽略通用选择器
否定伪类中的选择器计数与任何其他类似,但否定本身不计为伪类。
连接三个数字abc(在具有大基数的数字系统中)给出了特殊性。
示例:
* / * a = 0 b = 0 c = 0->特异性= 0 * /
LI / * a = 0 b = 0 c = 1 - specific = 1 * /
UL LI / * a = 0 b = 0 c = 2 - 特异性= 2 * /
UL OL + LI / * a = 0 b = 0 c = 3 - 特异性= 3 * /
H1 + * [REL = up] / * a = 0 b = 1 c = 1 - 特异性= 11 * /
UL OL LI.red / * a = 0 b = 1 c = 3 - 特异性= 13 * /
LI.red.level / * a = 0 b = 2 c = 1 - 特异性= 21 * /
#x34y / * a = 1 b = 0 c = 0->特异性= 100 * /
#s12:not(FOO)/ * a = 1 b = 0 c = 1 - specific = 101 * /
Which selector is stronger?
#nav li.current
or
div #nav li
and second
a.test
or
.test .test
What is the answer?
解决方案From the spec:
A selector's specificity is calculated as follows:
- count the number of ID selectors in the selector (= a)
- count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
- count the number of type selectors and pseudo-elements in the selector (= c)
- ignore the universal selector
Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
Examples:
* /* a=0 b=0 c=0 -> specificity = 0 */ LI /* a=0 b=0 c=1 -> specificity = 1 */ UL LI /* a=0 b=0 c=2 -> specificity = 2 */ UL OL+LI /* a=0 b=0 c=3 -> specificity = 3 */ H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 11 */ UL OL LI.red /* a=0 b=1 c=3 -> specificity = 13 */ LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */ #x34y /* a=1 b=0 c=0 -> specificity = 100 */ #s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 101 */
这篇关于哪个CSS选择器更强?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文