当 top 没有设置时,为什么 position: absolute div 没有与其兄弟重叠
When top is not set, why a position: absolute div is not overlapped with its siblings
上下文:当 position:absolute
<div>
直接在 <body>
中时,并且有一个 <div>
作为它的兄弟姐妹,就像在 JSFiddle 中一样.
问题:当 top
属性 未明确设置时,为什么 position:absolute
<div>
不与其兄弟重叠。
根据我的理解,但可能不正确,如果 <div>
设置为 position:absolute
,它将相对于 body if none of its parents and parents' parents 定位设置为 position:relative
。所以 top
position:absolute
<div>
的 属性 应默认为 body
原点,并且两个 div
应重叠。
代码在这里:
#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, while height: auto
is treated as a
height based on the content; or if bottom
is also auto
, the
element is positioned where it should vertically be positioned if it
were a static element.
所以它会根据bottom
或top
定位,但是因为你的例子中有none,所以它被定位为静态元素.
旧答案:
因为你设置了bottom: 0;
所以它粘在底部。
上下文:当 position:absolute
<div>
直接在 <body>
中时,并且有一个 <div>
作为它的兄弟姐妹,就像在 JSFiddle 中一样.
问题:当 top
属性 未明确设置时,为什么 position:absolute
<div>
不与其兄弟重叠。
根据我的理解,但可能不正确,如果 <div>
设置为 position:absolute
,它将相对于 body if none of its parents and parents' parents 定位设置为 position:relative
。所以 top
position:absolute
<div>
的 属性 应默认为 body
原点,并且两个 div
应重叠。
代码在这里:
#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
定位,但是因为你的例子中有none,所以它被定位为静态元素.
旧答案:
因为你设置了bottom: 0;
所以它粘在底部。