我知道,任何具有position:absolute属性的元素都将相对于最近的祖先元素定位,该祖先元素具有诸如absolute或relative等定位属性。这在各种答案中都有提到,例如这里。同时,在w3schools网站上也有介绍,这里...
使用position: absolute;属性的元素相对于最近的已定位祖先(而不是相对于视口,如fixed)进行定位。
然而,插入静态元素似乎会打破这个规则并移动绝对定位的元素。我想了解为什么会发生这种情况。请参见下面的代码片段。
如果将静态元素更改为绝对定位,则后续元素将按照最近的定位祖先规则正常显示。
div.relative {
position: relative;
width: 440px;
height: 600px;
border: 3px solid #73AD21;
}
div.static {
position: static;
width: 200px;
height: 100px;
border: 3px solid #73ADff;
}
div.absolute {
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
div.absolute2 {
left:210px;
position: absolute;
width: 200px;
height: 100px;
border: 3px solid #ffAD21;
}
<div class="relative">This div element has position: relative;
<div class="static">This div element has position: static</div>
<div class="absolute">This div element has position: absolute, but is positioned relative to the preceding static element, not the first positional ancestor.;</div>
<div class="absolute2">This div element also has position: absolute;</div>
</div>