2.3-34 层叠性和选择器权重计算
1、定义
(1)层叠性:多个选择器可以同时作用于同一个标签,效果叠加
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
p{
color:red;
}
.spec{
font-style:italic;
}
#para{
text-decoration:underline;
}
</style>
</head>
<body>
<p id="para" class="spec">我是段落</p>
</body>
</html>
2、层叠性的冲突处理
当多个选择器定义的属性有冲突时:
id权重>class权重>标签处理;
3、复杂选择器权重计算
复杂选择器可以通过(id的个数,class的个数,标签的个数)的形式,计算权重;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1 #box2 p{
/* (2,0,1) */
color:red;
}
#box1 div.box2 #box3 p{
/* (2,1,2) div .box2类拆开看*/
color:green;
}
.box1 .box2 .box3 p{
/* (0,3,1) */
color:blue;
}
</style>
</head>
<body>
<div id="box1" class="box1">
<div id="box2" class="box2">
<div id="box3" class="box3">
<p>我是段落</p>
<p>我是段落</p>
<p>我是段落</p>
</div>
</div>
</div>
</body>
</html>
4、!important提升权重
如果我们需要将某个选择器的某条属性提升权重,可以再属性后面写!important;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1 #box2 p{
/* (2,0,1) */
color:red;
}
#box1 div.box2 #box3 p{
/* (2,1,2) div .box2类拆开看*/
color:green;
}
.box1 .box2 .box3 p{
/* (0,3,1) */
color:blue;
}
p{
color:red;
}
.spec{
font-style:italic;
}
#para{
text-decoration:underline;
}
</style>
</head>
<body>
<p id="para" class="spec">我是你爸爸</p>
</div>
</div>
</div>
</body>
</html>
很多公司不允许使用!important,因为这会带来不经意的样式冲突;
权值相同,就近原则