如何使用 z-index 进行相对定位?
我的 z-index
和我的代码有问题。我想在每一行上都有一个弹出窗口,相对于该行定位。所以我创建了这段代码:
.level1
{
position:relative;
z-index:2;
}
.level2
{
position:relative;
z-index:3;
}
.popup
{
position:absolute;
left:0px;
top:10px;
width:100px;
height:100px;
background:yellow;
z-index:4;
}
<div class="level1">
<div class="level2">
<input type="text" value="test1" />
<div class="popup">test1</div>
</div>
<div class="level2">
<input type="text" value="test2" />
<div class="popup">test2</div>
</div>
</div>
I have a problem with z-index
and my code. I want to have a popup on every row, positioned relative to that row. So I created this code:
.level1
{
position:relative;
z-index:2;
}
.level2
{
position:relative;
z-index:3;
}
.popup
{
position:absolute;
left:0px;
top:10px;
width:100px;
height:100px;
background:yellow;
z-index:4;
}
<div class="level1">
<div class="level2">
<input type="text" value="test1" />
<div class="popup">test1</div>
</div>
<div class="level2">
<input type="text" value="test2" />
<div class="popup">test2</div>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您在元素上设置
position:relative
时,您就建立了一个新的包含块。该块内的所有定位都是相对于它的。在该块内的元素上设置 z-index 只会改变其相对于同一块内其他元素的图层。
我不知道有任何解决方法。
When you set
position: relative
on an element then you establish a new containing block. All positioning inside that block is with respect to it.Setting z-index on an element inside that block will only alter its layer with respect to other elements inside the same block.
I'm not aware of any work-arounds.
尝试将负值的 z-index 添加到后面的 div
try adding z-index with negative values to the back divs
您可以将
z-index
与relative
位置结合使用。您只需指定position:relative
。如果你真的想让它看起来像弹出来,我建议使用box-shadow
You can use
z-index
with therelative
position. You just need to specifyposition: relative
. If you really want it to look like it is popping up, I suggest usingbox-shadow
Z-Index 是一种规则顺序,仅当两个或多个元素重叠时结果才可见。这意味着,如果您希望具有与绝对位置相同的 z-index 行为,则需要使它们重叠。相对位置不会使它们重叠,因此例如在本例中,为了使这两个 div 重叠,我必须将第二个 div 的顶部设置为 -50px。
Z-Index is a rule order which results will be visible ONLY when two or more elements overlap. This means that if you want to have same z-index behaviour as in absolute position you'll need to make them overlap. Position relative don't make them overlap, so for example in this example, to make this two divs to overlap, I have to set the second one's top to -50px.