为什么'position:absolute'元素不能相对于'position:static'的父元素定位?

Cu1*_*ure 6 html css position absolute

有人可以解释一个position: absolute;只能与最近的非position: static;父母相关的原因吗?

元素相对于position: static;其父元素无法定位的原因是什么?

nea*_*ick 5

我相信这背后的原因是您可以相对于不只是该元素的直接父元素的元素定位绝对元素。因为position: static是默认值,所以让它成为元素是否应该相对于该父元素定位自身的决定因素是有意义的。

例如,我可以使用以下 html 相对于其祖父定位元素:

<div id="grandparent" style="position:relative">
    <div id="parent">
       <div id="child" style="position:absolute;top:0">
       </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 正确的。与绝对定位元素相关的元素称为其[包含块](http://www.w3.org/TR/CSS21/visudet.html# contains-block-details)。我刚刚回忆了一个使用 position 属性来控制哪个元素是 [this section](http://www.w3.org/TR/CSS21/visufx.html) 中给出的包含块的示例,它描述了溢出属性. 该示例表明,如果绝对定位元素的包含块是其祖父或其他远祖,则绝对定位元素不受其父元素的溢出属性的影响。 (3认同)