我有一个.link类,下面有一个:: after伪元素(作为悬停时的盒子阴影)。
.bg {
background-color: aqua;
height: 100vh;
}
.link {
position: relative;
font-weight: bold;
}
.link::after {
content: '';
position: absolute;
z-index: -1;
top: 0;
right: 0;
bottom: 0;
left: 0;
box-shadow: 0 0 0 1em #888888 inset;
opacity: 0;
}
.link:hover::after {
opacity: 1;
}
<div class="bg">
<p class="link">Link</p>
</div>
但是,当我向包含的div元素添加背景颜色时,它会覆盖框阴影。我试过添加
position: absolute;
z-index: -2;
虽然堆叠是正确的,但是这会导致div的调整大小问题。我想知道是否有一种首选的方法将伪元素放在bg层之上但在原始链接类之后?谢谢!
将z-index:0
(或任何值)添加到背景元素以创建堆叠内容并避免伪元素移动到后面:
.bg {
background-color: aqua;
height: 100vh;
position:relative;
z-index:0; /* added */
}
.link {
position: relative;
font-weight: bold;
}
.link::after {
content: '';
position: absolute;
z-index: -999; /*you can put any negative value now*/
top: 0;
right: 0;
bottom: 0;
left: 0;
box-shadow: 0 0 0 1em #888888 inset;
opacity: 0;
}
.link:hover::after {
opacity: 1;
}
<div class="bg">
<p class="link">Link</p>
</div>
相关:Why elements with any z-index value can never cover its child?