绝对定位的 div 的相对定位的兄弟元素已经移动到上方。

3
在一个相对定位的div#out中,有一个绝对定位的div#in。div#in被拉出了文档流,并通过将top、bottom、left和right坐标设置为0而覆盖div#out。虽然这样没问题,但我不明白的是,如果我给div#sibling设定position:relative,它会出现在div#in上方。
我已经检查了所有div元素的z-index属性,它们都是"auto",即相当于0。
我使用的版本是Version 45.0.2454.101 Ubuntu 14.04 (64-bit),但我认为这只是我的误解,而不是浏览器的问题。
非常感谢您的帮助。
<style>
    #out { 
        border: 1px solid red;
        background: red;
        position: relative;
    }
    #in { 
        border: 1px solid green;
        background: green;
        position: absolute;
        top:0;
        right:0;
        bottom: 0;
        left: 0;
    }
    #sibling{
        position:relative;
    }
</style>

<div id="out"> 
    This is the outer div<br>
    position relative

    <div id="in">inner div position absolute</div>
    <div id="other">other div position static </div>
    <div id="sibling">sibling position relative </div>
</div>

这是因为您的“in”具有绝对定位,而且您已将顶部、底部、右侧和左侧的所有内容设置为0。请删除这些行并添加“float:left”。 - tanjir
为什么不将您的“in”元素的z-index设置为大于“0”呢? - A.Sharma
@tanjir 我原以为将div#in的坐标设置为top、bottom、left就可以覆盖div#out中的所有元素,除了绝对定位的元素。div#relative没有任何坐标。我认为没有坐标的相对定位元素的行为类似于静态元素,但也许我在这里是错的。 - Douglas Tyding
@A.Sharma 我知道我可以通过z-index来解决这个问题,但我正在尝试理解它的行为。另一个有趣的点是,如果您在HTML中将elem div#sibling放置在div#inner上方,它将移动到伸展的div#in下面。这是我在当前位置期望的行为。 - Douglas Tyding
1个回答

0
根据w3schools的说法:
一个具有更高堆叠顺序的元素总是在具有较低堆叠顺序的元素前面。 注意:z-index只对定位元素(position:absolute、position:relative或position:fixed)起作用。
当您给予相对于#sibling的位置时,由于您的HTML顺序,它会出现在#in上方。
解决方案: 给#in增加更高的z-index。
CSS
#in { 
        border: 1px solid green;
        background: green;
        position: absolute;
        top:0;
        right:0;
        bottom: 0;
        left: 0;
        z-index:10;
    }

#sibling{
    position:relative;
    z-index:5;
}

HTML

<div id="out"> 
    This is the outer div<br>
    position relative

    <div id="in">inner div position absolute</div>
    <div id="other">other div position static </div>
    <div id="sibling">sibling position relative </div>
</div>

或者

CSS

#in { 
        border: 1px solid green;
        background: green;
        position: absolute;
        top:0;
        right:0;
        bottom: 0;
        left: 0;
    }

#sibling{
   //you can remove position
   //position:relative;
}

HTML

<div id="out"> 
    This is the outer div<br>
    position relative
    <div id="sibling">sibling position relative </div>
    <div id="in">inner div position absolute</div>
    <div id="other">other div position static </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接