持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第10天,点击查看活动详情
今天我们来介绍一下css优先级和优先级的权重计算。
css优先级
不同选择器具有不同的优先级,优先级高的选择器样式会覆盖优先级低的选择器样式。
优先级公式: 继承 < 通配符选择器 < 标签选择器 < 类选择器 < id选择器 < 行内样式 < !important;
!important写在属性值的后面,分号的前面;!important不能提升继承的优先级,只要是继承优先级最低!实际开发中不建议使用!important。
代码演示:
<style>
body {
color: red;
}
div {
color: #000;
}
.box {
color: blue;
}
#one {
color: orange;
}
</style>
<body>
<div>11111</div>
<div class="box">11111</div>
<div class="box" id="one">11111</div>
<div class="box" id="one" style="color: greenyellow;">11111</div>
</body>
浏览器效果:
css优先级权重计算
复合选择器之间的优先级,需要权重计算以判断最终哪个选择器优先级最高会生效。
权重叠加计算公式(每一级之间不存在进位)
比较规则:
- 先比较第一级数字,如果比较出来了,之后的统统不看;
- 如果第一级数字相同,此时再去比较第二级数字,如果比较出来了,之后的统统不看;
- 如果最终所有数字都相同,表示优先级相同则比较层叠性(谁写在下面,谁说了算!);
- 注意点: !important如果不是继承,则权重最高。
代码演示:
<style>
(0,1,0,1)
div #one {
color: orange;
}
(0,0,2,0)
.father .son {
color: skyblue;
}
(0,0,1,1)
.father p {
color: red;
}
(0,0,0,2)
div p{
color: pink;
}
</style>
<body>
<div class="father">
<p class="father" id="one">p</p>
</div>
</body>
明显第一个复合选择器的优先级最高,于是p文字应该是橙色的。