选择器权重
1.相同选择器:根据书写顺序 后面的会覆盖前面的
2.不同选择器:ID(100)> CLASS(10)> element(1)
3.层级选择器:按权重累加计算
<!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>
.myTitle {
color: red;
color: green;
color: yellow;
}
.title {
color: red;
}
#txt {
color: blue;
}
h1 {
color: black;
}
/* 层级选择器 */
/* 10 + 100 = 110 */
.box #text{
color: red;
}
/* 100 + 1 = 101 */
#box2 h2{
color: green !important;
}
/* !important 设置最高权重 */
</style>
</head>
<body>
<h1 class="myTitle">相同选择器</h1>
<h1 class="title" id="txt">hello world</h1>
<div class="box" id="box2">
<h2 id="text">层级选择器</h2>
</div>
</body>
可以用!important来设置最高权重,一般工作中基本不会用id。
引用别人的代码或样式想修改但权重不够的话就用!important就可以了。
</html>
样式权重:
权重:内联样式高于嵌入样式高于外部样式
HTML部分:
<!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>
<!-- 外部样式(实际工作中大部分会用外部样式) -->
<link rel="stylesheet" href="common.css">
<!-- 嵌入样式 -->
<style>
h1{
color: blue;
}
</style>
<!-- 权重:内联高于嵌入高于外部样式 -->
</head>
<body>
<!-- 内联样式,行内样式,权重要高于嵌入样式 -->
<h1 style="color: red;">hello world</h1>
</body>
</html>
CSS代码:
h1{
color: white;
}