我尝试将一个子 div 放置在其父级元素下方并位于其他元素上方。
.box1{
background-color: blue;
width: 500px;
height: 100px;
position: relative;
z-index: 3;
}
.box2{
position: absolute;
background-color: red;
width: 200px;
height: 100px;
left: 30%;
top: 20px;
z-index: 2;
}
.box3{
background-color: yellow;
width: 500px;
height: 100px;
z-index: 1;
}
<div class="box1">
<div class="box2"></div>
</div>
<div class="box3"></div>
我想将红色矩形放置在蓝色矩形下方和黄色矩形上方。我将 z-index 放在其中三个上。然而,这不起作用。
你对此有何看法?谢谢!
更新:虽然框的顺序正确,但是现在无法单击这些框内的元素。
您可以在此处查看错误:https://jsfiddle.net/p1xd6zah/
最佳答案
您可以使用 z-index
进行黑客攻击:
您可以将
z-index: -1
添加到box2
。 (将子级堆叠在父级下方)将
z-index: -2
和position:relative
添加到box3
(现在将其堆叠在后面box2
)
从 box1
中删除 z-index
- 请参阅下面的演示:
.box1 {
background-color: blue;
width: 500px;
height: 100px;
position: relative;
}
.box2 {
position: absolute;
background-color: red;
width: 200px;
height: 100px;
left: 30%;
top: 20px;
z-index: -1;
}
.box3 {
background-color: yellow;
width: 500px;
height: 100px;
z-index: -2;
position: relative;
}
<div class="box1">
<div class="box2"></div>
</div>
<div class="box3"></div>
关于html - 使用 z-index 将元素定位在 div 下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46200477/