我编写了一个简单的代码,其中包含一个主框,其中包含两个较小的框。
我已将较小的盒子的位置设置为绝对位置,以便根据它们的父级设置它们的位置。
我想做的是把 son2
div 放在前面,因为现在被 son
div
我尝试了 z-index
属性,但(如我所料)我的元素在 parent
元素下,而不是在小蓝框下
#parent {
position: absolute;
background-color: red;
width: 100px;
height: 100px;
margin-top: 200px;
margin-left: 200px;
}
#son2 {
position: absolute;
background-color: green;
width: 50px;
height: 50px;
margin-top: 20px;
}
#son {
position: absolute;
background-color: blue;
width: 50px;
height: 50px;
margin-top: 10px;
}
<div id="parent">
<div id="son2"></div>
<div id="son"></div>
</div>
Codepen 上的演示:https://codepen.io/mattiasu96/pen/KbpyNQ
最佳答案
微小的变化(只需将 z-index: 1;
添加到 son2
)。
顺便说一句,你不想为父级设置 position: absolute
除非你也需要改变它的自然位置,否则使用 position: relative
这样它就可以正常呈现,但绝对定位的子项仍会按预期运行。
我已经删除了父级的边距,这样您就不必在代码段中滚动来查看 div,但如果您在原始问题中需要这样做,则没有区别。
#parent {
position: relative;
background-color: red;
width: 100px;
height: 100px;
}
#son2 {
position: absolute;
background-color: green;
width: 50px;
height: 50px;
margin-top: 20px;
z-index: 1;
}
#son {
position: absolute;
background-color: blue;
width: 50px;
height: 50px;
margin-top: 10px;
}
<div id="parent">
<div id="son2"></div>
<div id="son"></div>
</div>
关于html - 选择哪个重叠的 div 在上面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733102/