1,样式冲突
当我们通过不同的选择器,选中相同的元素,并且为相同的样式设置不同的值时,此时就发生了样式的冲突,这时用到的样式就由选择器的权级(优先级)决定了。
2,选择器的优先级
选择器 | 权值 | 优先级 |
!important | 10000 | 5 最高优先级(慎用) |
内联样式 | 1000 | 4 |
ID选择器 | 100 | 3 |
class选择器 | 10 | 2 |
元素选择器 | 1 | 1 |
通配符选择器 | 0 | 没有优先级(最低) |
注意:
1、比较优先级时,需要将所有选择器的优先级进行相加计算,最后优先级越高,则优先显示
2、(并集选择器)分组选择器是单独计算的
3、如果优先级计算后相同,此时则优先使用靠下的样式
4、选择器的累加,不会超过上一级数量级,例如:类选择器再高也不会超过id选择器 量变达不到质变
一般来说:
选择器越具体,优先级越高
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择器的权重</title>
<style>
#a{
background-color: red;
}
.b{background-color: pink;}
[title] {
color: blue;
}
</style>
</head>
<body>
<div id="a" class="b b1 b2 b3" title="c">
那是一块木头
<span>不,那是一只鳄鱼</span>
<em>那就是一块木头</em>
</div>
</body>
</html>
则结果显示为红色背景
如果想要越级到达巅峰,那么只需要在样式后边加上!important
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择器的权重</title>
<style>
#a{
background-color: red;
}
div.b{background-color: pink !important;}
[title] {
background-color: chocolate;
}
</style>
</head>
<body>
<div id="a" class="b b1 b2 b3" title="c">
那是一块木头
<span>不,那是一只鳄鱼</span>
<em>那就是一块木头</em>
</div>
</body>
</html>
结果显示变成粉色背景
3,其他选择器
伪类选择器
属性选择器
伪类选择器和属性选择器的权重相当于类选择器的权重,权级为2级。
伪元素选择器
伪元素选择器的权重相当于元素选择器的权重,权级为1级。
子代选择器
后代选择器
子代和后代有可能是元素选择器、类选择器、id选择器,因此要根据具体情况来具体分析。