关于CSS的优先级,面试的时候用到最多。这是css排版必须掌握,也是很多网页前端开发人员比较容易忽视的知识点。下面,这篇文章将详细说说CSS的优先级情况,看看它们到底有什么规律:

第一:CSS存放位置的优先级规律

标签内嵌样式 > 页面内部样式表 > 外联样式表

这里有一点要注意:“页面内部样式表” 的位置一定要比“ 外联样式表” 离定义样式标签的距离近,否则“外联样式表”的优先级会比 “页面内容样式表”的高。所以这条规律总结是离标签内容最近的样式才具有最高的权重性。

<link href="yx.css" type="text/css" rel="stylesheet"/> (这里外联样式为:#test p.pra{color:red;})  <!–页面内部样式表–>

<style type="text/css">
#test p.pra{color:green;}
</style> <!–外联样式表–>

<div id="test" class="test" >
<p class="pra" style="color:yellow;color:#C09;">这是一段文字!</p>
<!–标签内嵌样式–>
</div>

通过前面所说的规律,我们可知 标签的字体颜色最终为 color:#C09;

第二:样式选择器规律

important的权重为1,0,0,0

ID的权重为0,1,0,0

类的权重为0,0,1,0

标签的权重为0,0,0,1

伪类的权重,属性的权重为0,0,1,0

伪对象的权重为0,0,0,1

通配符的权重为0,0,0,0

每一个选择器都有一个对应的数值,通过上面的数据我们知道important的权重型最高为1000,通配符的权重型最低为0;在对各样式计算权重数值时,我们有如下方法:

#test p.pra{color:green!important;}   /*权重为100+1+10+1000=1111*/

#test p.pra{color:green;} /*权重为100+1+10=111*/

等依次类推……

第三:当样式选择器规律 遇到 css存放位置的优先级规律 时

假如有如下代码:

<link href="yx.css" type="text/css" rel="stylesheet"/>(这里外联样式为:#test p.pra{color:red!important;})

<style type="text/css">
#test p.pra{color:green!important;}
</style>

<div id="test" class="test" >
<p class="pra" style="color:yellow;">这是一段文字!</p>
</div>

那么,请问这里颜色什么? 通过浏览器测试,标签的字体颜色最终为 color:green ;所以,我们可以知道,当样式选择器规律 遇到 css存放位置的优先级规律 时,它会视而不见,继续走下去。所以,我们在衡量样式的优先级时,要先依照样式选择器规律,再去考虑css存放位置的优先级规律。

最后献上ie6的奇葩反应:

<link href="yx.css" type="text/css" rel="stylesheet"/>(这里外联样式为:#test p.pra{color:red!important;})

<style type="text/css">
#test p.pra{color:green!important;}
</style>

<div id="test" >
<p style="color:yellow!important;color:#000">这是一段文字!</p>
</div>

你猜在ie6和别的浏览器有什么区别? ie6 为color:green ,别的浏览器为color:yellow。不解释!