绝对位置不起作用
我试图将 id 为“absPos”的 div 放置在相对于其父 div 的绝对位置。但它不起作用,div被放置在页面的左上角。
我的代码示例如下,
<html>
<body>
<div style="padding-left: 50px;">
<div style="height: 100px">
Some contents
<div>
<div style="height: 80px; padding-left: 20px;">
<div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
Some text
</div>
</div>
</body>
</html>
你能帮我解决这个问题吗? 在我的实际情况中,我必须放置背景图像而不是红色背景颜色。
问候
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
具有绝对定位的元素从其
offsetParent
定位,即最近的祖先,即 也已定位。在您的代码中,所有祖先都不是“定位”元素,因此 div 相对于 body 元素有偏移,即offsetParent
。解决方案是将
position:relative
应用于父 div,强制其成为定位元素和子元素的offsetParent
。Elements with absolute positioning are positioned from their
offsetParent
, the nearest ancestor that is also positioned. In your code, none of the ancestors are "positioned" elements, so the div is offset from body element, which is theoffsetParent
.The solution is to apply
position:relative
to the parent div, which forces it to become a positioned element and the child'soffsetParent
.如果要放置具有绝对位置的元素,则需要基本元素具有默认值以外的位置值。
在您的情况下,如果您将父 div 的位置值更改为“相对”,则可以解决该问题。
If you are placing an element with absolute position, you need the base element to have a position value other than the default value.
In your case if you change the position value of the parent div to 'relative' you can fix the issue.
您需要声明父 div 本身
position:relative
或position:absolute
。在本例中,
relative
就是您要查找的内容。You need to declare the parent div either
position: relative
orposition: absolute
itself.relative
is what you're looking for in this case.您需要首先给出父 div
relative
位置:You need to give parent div
relative
position first:如果像我一样,您试图将一个元素定位在另一个元素之上,则浮动元素需要位于另一个元素的内部,而不是作为兄弟元素。现在您的
position:absolute;
可以工作了!If, like me, you were trying to position an element over another element, the floating element needs to be inside of the other, not as siblings. Now your
position:absolute;
can work!您还可以将 Position:absolute 应用到父 Div。总代码如下
You can also Apply Position:absolute to the Parent Div. Total Code below