下面是W3官方的描述
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.
?
简单的翻译下:
- 计算ID选择器的个数(= a)
- 计算类选择器、属性选择器、伪类的个数(= b)
- 计算类型(标签tag)选择器、伪元素的个数(= c)
- 忽略通用选择器(*)
在否定的伪类里面的选择器同样按照上面的方法计算,但否定的伪类本身不做计算。
?
最后连接这三个数值来表示特性:a-b-c
可以看下下面的例子:
?
* /* 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 */
?有一点要注意的是,b、c是不进位的。就是说b再大也不会改变a的值,c再大也不会改变b的值。
?