4 CSS选择器的权重

谁的选择器权重大,在浏览器上就会选择谁的选择器

内联样式的选择器权重为 1000
id选择器权重为 100
类选择器权重为 10
标签选择器权重为 1
权重计算永不进位
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>选择器的权重</title>
	<style type="text/css">
	/*那么怎么数它们的数量呢?
	首先判断ID选择器几个;类选择器几个;标签选择器几个*/
		/*1 0 0*/
		#b{
			color: green;
		}
		/*0 0 1*/
		div{
			color: red;
		}
		/*0 1 0*/
		.b{
			color: purple;
		}
	</style>
</head>
<body>
	<div>a</div>
	<div class="b" id="b" style="color: orange;">b</div>
	<!-- 行内的权重大于嵌入式的权重 -->

</body>
</html>
  • 深入了解一下权重
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>CSS选择器权重深入</title>
	<style type="text/css">
		/*001*/
		p{
			color: gray;
		}
		/*003*/
		div div p{
			color: yellow;
		}
		/*010*/
		.active{
			color: purple;
		}
		/*011*/
		div .active{
			color: black;
		}
		/*012*/
		div div .active{
			color: blue;
		}
		/*120*/
		.wrap1 #box2 .active2{
			color: green;
		}
		/*201*/
		#box1 #box2 p{
			color: red;
		}
		/*继承来的属性,权重非常低几乎为0*/
		#box1 #box2 #box3{
			color: orange;
		}
	</style>
</head>
<body>
	<div class="wrap1" id="box1">
		<div class="wrap2" id="box2">
			<div class="wrap3" id="box3">
				<p class="actice">MJJ是什么颜色</p>
			</div>
		</div>
	</div>
 
</body>
</html>

! import

注意:

还有一种不讲道理的!import方式来强制让样式生效,但是不推荐使用。因为大量使用!import的代码是无法维护的。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>!import讲解</title>
	<style type="text/css">
		div{
			color: purple !important;
		}
	</style>
</head>
<body>
	<div style="color:red;">a</div>
</body>
</html>

当遇到2个以上!important 时,权重值高的有优先权。

posted @ 2022-08-04 16:11  角角边  Views(58)  Comments(0)    收藏  举报