您的位置:首页 > Web前端 > CSS

CSS优先级

2015-08-22 00:09 543 查看

CSS优先级

在CSS官方文档里关于其优先级是这样的:

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

上述表述意思是这样的

如果含有ID选择器,则a=1;

如果含有class选择器,则b=1;

含有标签选择器或伪选择器,则c=1

忽略
*
选择器

将上述规则应用在选择器中,符合对应条件的就加1,最后将其值依次排在百位十位个位上,哪个值最大,则其对应的样式生效。

官方文档示例:

selectorspecificity
*a=0 b=0 c=0 -> specificity = 0
LIa=0 b=0 c=1 -> specificity = 1
UL LIa=0 b=0 c=2 -> specificity = 2
UL OL+LIa=0 b=0 c=3 -> specificity = 3
H1 + *[REL=up]a=0 b=1 c=1 -> specificity = 11
UL OL LI.reda=0 b=1 c=3 -> specificity = 13
LI.red.levea=0 b=2 c=1 -> specificity = 21
x34ya=1 b=0 c=0 -> specificity = 100
s12:not(FOO)a=1 b=0 c=1 -> specificity = 101
举例说明上述规则:

<div id="test">
<span>Text</span>
</div>


其对应的css:

div#test span { color: green }  /*#1*/
div span { color: blue }       /*#2*/
span { color: red }           /*#3*/


分析如下:

#1. 其specificity=100*1+1+1=102;

#2. 其specificity=1+1=2;

#3. 其specificity=1;

由此可见,#1的权重最大,因此其显示绿色。

我们在设置样式的时候尽量使用优先级来确定其样式,当然,我们可以使用
!important
来确定样式,使用
!important
则不再遵守优先级规则,其样式会覆盖别的对应的样式,因此我们要尽量减少使用
!important
,尤其不要在全站样式或者插件中使用。

当然,我们也可以使用
!important
来覆盖上一个
!important
选择器,只要书写在其上一条
!important
下面即可,或者在该选择器中添加一条标签选择器,例如:

table td    {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: