关于css优先级

本文详细介绍了CSS中不同选择器的优先级,包括内部样式表、ID选择器、类选择器和标签选择器,并通过示例代码展示了!important声明如何影响样式应用。

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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值