问题:
从一段简单代码看问题:
给一个本身有background/background-image的div元素,设置一个伪元素作为背景颜色,希望的层叠顺序是看到div在上放,伪元素在下方
<div class="box"></div>
.box {
position: relative;
width: 100px;
height: 100px;
background: red;
/* transform: translateX(-10px); */
/* z-index: 10; */
}
.box::after {
position: absolute;
content: '';
top: 0;
right: 0;
bottom: 0;
left: 0;
background: blue;
z-index: -1;
}
上述样式,显示红色在上, 符合预期;
.box {
position: relative;
width: 100px;
height: 100px;
background: red;
/* transform: translateX(-10px); */
z-index: 10;
}
.box::after {
position: absolute;
content: '';
top: 0;
right: 0;
bottom: 0;
left: 0;
background: blue;
z-index: -1;
}
上述样式显示蓝色在上,不符合预期;
问题原因:
为什么给父元素加了z-index数值或者transfrom,则红色不在最上方了呢?
因为如果想实现层叠效果,需要元素和对应的伪元素在同一层叠上下文中,所以不能让父元素创建层叠上下文。以下情况会创建层叠上下文:
- postion不为static,且设置z-index;
- transform不是none;
因此,给父元素设置z-index:10或者transform后,父元素和伪元素不在同一个层叠上下文中,子元素会覆盖父元素
网友评论