嵌入式绝对div和z-索引
问题描述:
我尝试实现一个下拉菜单,可以在不同的div中重新使用。嵌入式绝对div和z-索引
我使用position:relative
作为下拉菜单(所以它会出现在打开它的按钮下面)。问题是,下拉菜单只覆盖它的父div:如果下拉菜单重叠到另一个(不是父母)div,无论我设置的z-index如何,它都会覆盖。
有没有解决方案,使绝对定位项目超过一切?
(我必须用其他原因的z索引,我不能让菜单显示:相对)
.back, .front, .back2{
position: absolute;
width: 100px;
color: white;
line-height: 100px;
text-align: center;
}
.back {
position:relative;
z-index: 10;
top: 20px;
left: 20px;
background: red;
}
.back2 {
position:relative;
z-index: 10;
top: 50px;
left: 20px;
background: orange;
}
.front {
position: absolute;
z-index:20;
top: 60px;
left: 60px;
background: green;
}
<div class="back">
<span >Parent div1</span>
<div class="front">
<span >dropdown</span>
</div>
</div>
<div class="back2">
<span >someOtherDiv</span>
</div>
答
没有必要屈服于父母的z-index DIV。检查下面
.back, .front, .back2{
position: absolute;
width: 100px;
color: white;
line-height: 100px;
text-align: center;
}
.back {
position:relative;
top: 20px;
left: 20px;
background: red;
}
.back2 {
position:relative;
top: 50px;
left: 20px;
background: orange;
}
.front {
position: absolute;
z-index:20;
top: 60px;
left: 60px;
background: green;
}
<div class="back">
<span >Parent div1</span>
<div class="front">
<span >dropdown</span>
</div>
</div>
<div class="back2">
<span >someOtherDiv</span>
</div>
更新片断根据您的问题,你不能在这种情况下,从
parent div
删除z-index
您可以更新更大的z-index
到parent div
。 检查以下更新片段...
.back, .front, .back2{
position: absolute;
width: 100px;
color: white;
line-height: 100px;
text-align: center;
}
.back {
position:relative;
top: 20px;
left: 20px;
background: red;
z-index:10;
}
.back2 {
position:relative;
top: 50px;
left: 20px;
background: orange;
z-index:9;
}
.front {
position: absolute;
z-index:20;
top: 60px;
left: 60px;
background: green;
}
<div class="back">
<span >Parent div1</span>
<div class="front">
<span >dropdown</span>
</div>
</div>
<div class="back2">
<span >someOtherDiv</span>
</div>
其他原因(不涉及这个问题),我必须用父DIV的Z-index属性。有没有办法解决这个问题而不删除? – ForestG
@ForestG检查更新回答 –
谢谢,这是我一直在寻找的解决方案。 虽然正如您在第一个问题中指出的那样,如果没有z索引,我不会有问题...所以我正在考虑从项目中删除z-index解决方案,它们看起来不像一个广泛使用的良好做法。 – ForestG