上下文:当 position:absolute
<div>
直接在<body>
, 还有一个 <div>
作为它的 sibling ,如 JSFiddle .
问题:为什么 position:absolute
<div>
当 top
时不与其 sibling 重叠属性未明确设置。
据我了解但可能不正确,如果 <div>
设置为 position:absolute
,如果它的 parent 和 parent 的 parent 都没有被设置为 position:relative
,它将相对于 body 定位。 .所以 top
position:absolute
的属性<div>
应默认为 body
起源和两个div
s 应该重叠。
代码在这里:
#box_1 {
width: 200px;
height: 200px;
background: green;
}
#box_2 {
position: absolute;
left: 200px;
width: 200px;
height: 200px;
background: blue;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="box_1"></div>
<div id="box_2"></div>
</body>
</html>
最佳答案
更新后的答案:
这是因为默认的top
值是auto
所以它让浏览器计算上边缘位置。
来自 MDN :
For absolutely positioned elements, the position of the element is based on the
bottom
property, whileheight: auto
is treated as a height based on the content; or ifbottom
is alsoauto
, the element is positioned where it should vertically be positioned if it were a static element.
因此它将根据 bottom
或 top
进行定位,但由于您的示例中没有,它被定位为静态元素.
旧答案:
因为你设置了 bottom: 0;
所以它粘在底部。
关于css - 没有设置top的时候,为什么位置: absolute div is not overlapped with its siblings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53938462/