什么是选择器优先级(Specificity)

浏览器通过优先级来判断哪一些属性值与一个元素最为相关,从而在该元素上应用这些属性值。优先级是基于不同种类选择器组成的匹配规则。

我们可以先看一个例子:


HTML

<div id="content" class="content">
我是什么颜色
</div>

CSS:

#content {
color: red;
}
.content {
color: chartreuse;
}

 

那最后文字是什么颜色呢?答案很简单:红色

这就涉及到了优先级问题,同一块内容,我们同时用了 ID选择器 和 类选择器,因为 ID选择器 优先级大于 类选择器 , 所以最终显示为红色。


优先级的计算规则,CSS选择器的优先级关系是:

内联 > ID选择器 > 选择器 > 标签选择器


但是,浏览器具体的优先级算法是怎样的?可能还有些人不知道。《CSS REFACTORING》 中提到了算法的过程 。

A specificity is determined by plugging numbers into (a, b, c, d):

1、If the styles are applied via the style attribute, a=1; otherwise, a=0.

2、b is equal to the number of ID selectors present.

3、c is equal to the number of class selectors, attribute selectors, and pseudoclasses present.

4、d is equal to the number of type selectors and pseudoelements present.

翻译过来就是

CSS选择器的优先级是由 ABCD 的值来决定的,其中它们的值计算规则如下:

A 如果存在内联样式,那么 A = 1, 否则 A = 0;

B 的值等于 ID选择器 出现的次数;

C 的值等于 选择器 和 属性选择器 和 伪类E:link出现的总次数;

D 的值等于 标签选择器 和 伪元素(伪对象选择符E:first-letter等)出现的总次数 。


内联ID/属性/伪类(伪对象)标签选择器/伪元素(伪类)

li                                  /* (0, 0, 0, 1) */
ul li                               /* (0, 0, 0, 2) */
ul ol+li                            /* (0, 0, 0, 3) */
ul ol+li                            /* (0, 0, 0, 3) */
h1 + *[name=test]                   /* (0, 0, 1, 1) */
ul ol li.red                        /* (0, 0, 1, 3) */
li.red.level                        /* (0, 0, 2, 1) */
.a1.a2.a3.a4.a5.a6.a7.a8            /* (0, 0, 8, 0) */
#content                            /* (0, 1, 0, 0) */
li:first-child h2 .title            /* (0, 0, 2, 2) */
#nav .selected > a:hover            /* (0, 1, 2, 1) */
html body #nav .selected > a:hover  /* (0, 1, 2, 3) */