
css的优先级从低到高依次是:内部样式表的优先级为(1,0,0,0),id选择器优先级为(0,1,0,0),class选择器为(0。0,1,0),tag标签为(0。0,0,1)。除此之外,!important权重最高,比inline style还要高。
从字面意思就知道它最重要。
在这里插个题外话。
我之前一直错误的以为!important仅仅是css hack的一个写法。
我印象中!important是号称支持到ie7及以上的,不支持ie6的。不知道人没有也这么觉得。。。直到今天我才意识到我的错误。事实上在我知道了!important能够改变css优先级的的时候还知道了ie6也是认识!important的。仅仅只是IE6读取含有!important'的css属性是顺序读取的。这是IE6的一个非常典型的bug。比方:
<style type="text/css">
div{
background: red !important;
background: blue;
}
</style>
这个结果是div的背景为blue;假设这样:
<style type="text/css">
div{
background: blue;
background: red !important;
}
</style>
把两个属性倒换位置。结果背景为red。这说明IE6并不会对!important开放特权。
而是一视同仁。
比如:
情形一:div.test1 .span a 优先级 (0,0,2,2)。
情形二:span#xxx .songs li 优先级(0,1,1,2);
情形三:#xxx li 优先级 100 +1 (0,1,0。1);
直接上代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div .aa{color:orange;}/*(0,0,1。1)*/
.bn .aa{color:red;}/*(0。0。2,0)*/
#bb .aa{color:yellow;}/*(0。1,1,0)*/
#bb a{color:blue;}/*(0,1,0,1)*/
</style>
</head>
<body>
<div id="bb" class="bn">
<a style="color:gray;" href="#" class="aa">link</a>
<div>
</body>
</html>
代码运行后,link字体的颜色为gray,由于内部样式表的优先级最高。为(1,0,0。0)。
可是假设。给div .aa{color:orange!important;}这样一个属性,那么link字体的颜色就是orange了。