天天看点

css 层叠性 统计权重 优先级问题

1、层叠性:

当同一个元素被两个或多个选择器选中时,css会根据选择器的权重来决定使用哪一个选择器,权重低的会被权重高的层叠

2、统计权重:

权重大小:id选择器  > 类选择器 > 标签选择器

图解:

css 层叠性 统计权重 优先级问题

3、图2红色字体疑问处,权重问题代码实战:

  • 代码1:不同的选择器没有定位到元素,但都定位到了同一个标签层(权重为0)。假设有权重,权重不同时,权重大的为准:
  • 代码2:假设有权重,权重相同时,就近原则(css选择器从上到下以下面选择器为准):
<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>Document</title>

	<style type="text/css">
		#box3 {
				color: red;
			}
		.box2 .box3 {
			color: blue;
		}
		
	</style>
</head>

<body>
	<div id="box1" class="box1">
		<div id="box2" class="box2">
			<div id="box3" class="box3">
				<p>猜猜我是什么颜色</p>
			</div>
		</div>
	</div>
</body>
</html>
           
css 层叠性 统计权重 优先级问题
<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>Document</title>

	<style type="text/css">
		.box2 #box3 {
				color: red;
			}
		#box2 .box3 {
			color: blue;
		}
		
	</style>
</head>

<body>
	<div id="box1" class="box1">
		<div id="box2" class="box2">
			<div id="box3" class="box3">
				<p>猜猜我是什么颜色</p>
			</div>
		</div>
	</div>
</body>
</html>
           
css 层叠性 统计权重 优先级问题