一、CSS的优先级
1、案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#p1{
color: red;
}
.pp{
color: yellow;
}
p{
color: blue;
}
*{
color: yellow;
}
</style>
</head>
<body>
<p id="p1" class="pp" style="color: peachpuff;">我的颜色是?</p>
</body>
</html>
效果:
分析:对p有作用的样式为行内样式:style="color:peachpuff;"
说明行内样式的权重是最高的;
2、去掉行内样式后:
<p id="p1" class="pp">我的颜色是?</p>
效果:
分析:此时有作用的样式为:id选择器#p1{}
3、去掉id选择器后:
<style type="text/css">
.pp{
color: yellow;
}
p{
color: blue;
}
*{
color: yellow;
}
</style>
效果:
分析:此时有作用的样式为:类选择器,.p{}
4、去掉类选择器:
效果:
分析:标签选择器p{}的权重大于*{}
5、结论:
行内样式style="..." > id选择器#id > 类选择器.class > 标签选择器 > 通用选择器*
二、权重值
1、案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
a { color: yellow; }
div a{color: green;}
.demo a{color: black;}
#demo a{color: orange;}
div#demo a{color: red;}
</style>
</head>
<body>
<a href="#">应该是黄色</a>
<div class="demo">
<a href="">应该是黑色</a>
</div>
<div id="demo">
<a href="">应该是红色</a>
</div>
</body>
</html>
效果:
2、分析权重
当样式发生重叠冲突时,浏览器会根据权重大小进行渲染,谁的权重高就生效
选择器 | 权重值 |
通用选择器* | 0 |
标签选择器(a{} img{} body{},,,) | 1 |
类选择器(.nav{},,,) | 10 |
id选择器(#nav{}...) | 100 |
行内样式(<a style="..."></a>) | 1000 |
3、案例
#demo p .tt =>权重值为:100 + 1 + 10 =111
#demo .tt => 权重值为:100 + 10 = 110
选择器选择的范围越精确,优先级越高
<style type="text/css">
a { color: yellow; } /* 1 */
div a{color: green;} /* 1+1 */
.demo a{color: black;} /* 10+1 */
#demo a{color: orange;} /* 100+1 */
div#demo a{color: red;} /* 1+100+1 */
</style>
<a href="#">应该是黄色</a>
1)对于上述代码生效的只有第一个,所以是黄色
<div class="demo">
<a href="">应该是黑色</a>
</div>
2)对于上述代码生效的有以下样式
根据权重分析,生效的为黑色
<div id="demo">
<a href="">应该是红色</a>
</div>
3) 对于上述代码生效的样式如下:
根据权重分析,生效的为红色
三、实际应用
1、去掉最后一行的底边框
源代码:
<style>
#news{
list-style: none;
width: 370px;
}
#news li{
height: 40px;
line-height: 40px;
border-bottom: dashed;
}
#news li a {
color: gray;
text-decoration: none;
}
.last {
border: none;
}
</style>
<body>
<ul id="news">
<li><a href="#">新闻1</a></li>
<li><a href="#">新闻2</a></li>
<li><a href="#">新闻3</a></li>
<li><a href="#">新闻4</a></li>
<li class="last"><a href="#">新闻5</a></li>
</ul>
</body>
2、经分析,类选择器.last样式并未生效,因为#new li a的权重大于.last
#new li a => 100+1+1=102
.last => 10
3、解决:只需在.last前面加上#new 其权重就会大于带有底边的样式
#new li a => 100 + 1 + 1 =102
#new .last => 100 + 10 =110