层叠是css的一个特性,如果两个相同的属性作用于同一标签,它们会发生层叠。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{
color: pink;
}
.grandson {
font-style: italic;
color:blue;
}
#grandson {
color:red;
}
</style>
</head>
<body>
<div class="father" id="father">
<div class="son" id="son">
<div class="grandson" id="grandson">
abcdefg
</div>
</div>
</div>
</body>
</html>
如下:就是3个复合选择器
<style type="text/css">
#father .son div{ /* 1个id选择器, 1个类选择器 1个标签选择器*/
color: pink;
}
#father .son { /* 1个id选择器, 2个类选择器 但是没有直接命中 "abcdefg" */
font-style: italic;
color:blue;
}
.father .son .grandson{ /* 0个id选择器, 3个类选择器 */
color:red;
}
</style>
如果有多个复合选择器,同时作用于同一标签,优先级就不好计算。这时候就要通过比较权重,来选出优先级最高的选择器。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#father .son div{ /* 1个id选择器, 1个类选择器 1个标签选择器*/
color: pink;
}
#father .son { /* 1个id选择器, 2个类选择器 但是没有直接命中 "abcdefg" */
font-style: italic;
color:blue;
}
.father .son .grandson{ /* 0个id选择器, 3个类选择器 */
color:red;
}
#grandson{ /* 1个id选择器 0个类选择器 */
color:brown;
}
</style>
</head>
<body>
<div class="father" id="father">
<div class="son" id="son">
<div class="grandson" id="grandson">
abcdefg
</div>
</div>
</div>
</body>
</html>
层叠是css的一个特性, 如果多个选择器同时作用于同一个标签的同一个属性,那么它们之间要发生层叠,这个层叠是由优先级来决定。有时候优先级不能直接通过观察判断出来,如果要比较优先级就要使用权重。