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,最后将其值依次排在百位十位个位上,哪个值最大,则其对应的样式生效。
官方文档示例:
selector | specificity |
---|---|
* | 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.leve | 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 |
<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;}
相关文章推荐
- [HTML] CSS 下拉列表菜单
- WEB基础之:CSS
- Qt鼠标事件 我的鼠标样式
- css3背景颜色渐变
- NumberPicker 样式设置
- CSS中行高line-height属性的一些使用技巧
- CSS学习笔记之定位
- css position
- css3 transform transition 实现照片墙效果
- CSS3:绘制图形
- CSS实现绝对底部一个完美解决方案
- HTML简介(css简单的样式)
- 网页样式(css+js)tab自动切换的minisite
- css3 display:box
- CSS 3层嵌套居中布局
- CSS float 父元素高度自适应
- css3选择器
- RunJS推荐用于个人使用(使用方便JS、css实时预览、编辑、管理等功能)
- Qt自己的css简称qss
- Firebug折腾记_(2)HTML&CSS定位及调试小技巧