css的特性-层叠性
一、css的翻译是层叠样式表,那什么是层叠呢?
-
对于一个元素来说,相同属性我们通过不同的选择器进行多次设置
-
那么这些属性就会一层层的覆盖上去
-
最终只有一个会生效
<!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>Document</title> </head> <style> .box { color: red; } .one { color: blue; } .first { color: green; } .content { color: orange; } </style> <body> <div class="box one first content"> 我是div元素 </div> </body> </html>

二、如果那么多样式覆盖上去,到底那一个会生效呢
- 判断一:选择器的权重,权重大的生效,根据权重可以判断出优先级
- 判断二:先后顺序,权重相同时,后面设置的生效
三、那么如何知道元素的权重呢
- 按照经验,为了方便比较css属性的优先级,可以给css属性所处的环境定义一个权值(权重)
<!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>Document</title>
<style>
/* important权重:10000*/
.box {
color: red !important;
}
/* id选择器权重:100 */
#mant {
color: blue;
}
/* 类选择器、属性选择器,伪类权重:1 */
.box {
color: rgb(19, 19, 180);
}
/* 元素选择器:10 */
div {
color: blueviolet;
}
/* 统配选择器:0*/
* {
color: orange;
}
</style>
</head>
<body>
<!-- 内联权重:1000 -->
<div class="box" style="color: #000;">我是div元素</div>
</body>
</html>

四、css权重
- !important:10000
- 内联样式:1000
- id选择器:100
- 元素选择器:10
- 类选择器、伪类:1
- 统配选择器:0

本文详细介绍了CSS的层叠性,解释了当同一元素的相同属性被不同选择器设置时,如何确定生效的样式。内容包括选择器的权重计算、优先级判断以及权重的具体数值。通过示例代码展示样式覆盖的顺序,并总结了内联样式、ID选择器、类选择器等的权重值,帮助理解CSS样式的生效规则。
1647

被折叠的 条评论
为什么被折叠?



