考虑 HTML:
<html>
<body>
<div id="outer"><div id="inner"></div></div>
</body>
<html>
及其 CSS:
#inner {
height: 75px;
width: 75px;
background-color: red;
position: absolute;
margin-left: 20px;
}
#outer {
height: 1500px;
width: 150px;
background-color: green;
position:static;
margin-left: 100px;
}
据我了解,内部 div 应该距 html 元素有 20px 的左边距,而不是距外部 div 的左边距,因为外部 div 具有静态位置。 但内部 div 似乎总是相对于外部 div 定位自身。我在这里缺少什么?
如果有人可以帮忙,谢谢。
编辑:
来源:www.codecademy.com
最佳答案
position:absolute;
从正常流中删除元素并相对于最接近的定位祖先定位自身。如果不存在,它将自身定位到初始包含 block ,该包含 block 采用视口(viewport)的尺寸。 Reference .
尽管如此,对于 absolute
元素,您应该始终指定 x 和 y 尺寸(例如 top
和 left
),否则您可能会得到一些奇怪的行为,例如它相对于您正在观察的 static
祖先元素的定位。看看添加 top
和 left
后会发生什么:
#inner {
height: 75px;
width: 75px;
background-color: red;
position: absolute;
top: 0;
left: 0;
margin-left: 20px;
}
#outer {
height: 1500px;
width: 150px;
background-color: green;
margin-left: 100px;
}
<html>
<body>
<div id="outer">
<div id="inner"></div>
</div>
</body>
<html>
关于html - "position:absolute"在CSS中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36734582/