<style>
.box {
width: 200px;
height: 200px;
background-color: green;
}
.box .center {
width: 150px;
height: 150px;
background-color: blueviolet;
}
.flex {
display: flex;
justify-content: center;
align-items: center;
}
/* 30 */
.box .center .inner {
width: 100px;
height: 100px;
background-color: green;
}
/* 10+10 */
.box:hover .inner {
background-color: red;
}
</style>
<div class="box flex">
<div class="center flex">
<div class="inner"></div>
</div>
</div>
如上代码为什么hover有效果是红色,不是应该绿色不变吗,从优先级来看的也是绿色才对吧
###一个选择器的优先级可以说是由四个部分相加?(分量),可以认为是个十百千 —?四位数的四个位数:
- 千位:?如果声明在
[style](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes#attr-style)
?的属性(内联样式)则该位得一分。这样的声明没有选择器,所以它得分总是1000。 - 百位:?选择器中包含ID选择器则该位得一分。
- 十位:?选择器中包含类选择器、属性选择器或者伪类则该位得一分。
- 个位:选择器中包含元素、伪元素选择器则该位得一分。
因此我们可以知道
/* 0030 */
.box .center .inner {
width: 100px;
height: 100px;
background-color: green;
}
/* 0030 */
.box:hover .inner {
background-color: red;
}
两者优先级相同,根据位置确定关系,因此有红色。
ps: 在进行计算时不允许进行进位,例如,20 个类选择器仅仅意味着 20 个十位,而不能视为 两个百位,也就是说,无论多少个类选择器的权重叠加,都不会超过一个 ID 选择器。###
:hover属于伪类,从优先级来说,比类选择器高多了
###优先级:
0 important
1 行内元素
2 id
3 类和伪类
4 元素和伪元素
如优先级相同时,根据位置顺序确定优先关系
###伪类的权重>类名