jQuery DIV 绝对定位 - 在浏览器窗口调整大小后保持位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5563285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DIV absolute positioning - maintain position after browser window resize
提问by shanethehat
I am displaying divs with position absolute.
我正在显示具有绝对位置的 div。
.my_label{
list-style:none;
list-style-type:none;
position:absolute;
top:2px;
left:10px;
width:20px;
height:20px;
background-color:#FF1021;
}
once I re-size the browser window, all these divs stay at same position. and they're not absolute to the parent elements anymore. I want them to stay in relation with the surrounding objects. should I use position "relative" or is there another way? (also jQuery is welcome)
一旦我重新调整浏览器窗口的大小,所有这些 div 都会保持在相同的位置。并且它们不再是绝对的父元素了。我希望它们与周围的物体保持联系。我应该使用“相对”位置还是有其他方法?(也欢迎 jQuery)
thanks a lot
多谢
回答by shanethehat
To make an element position absolutely to it's parent, the parent must be set to position:relative
.
要使元素位置绝对与其父元素相关,必须将父元素设置为position:relative
。
For example:
例如:
<div id="parent" style="margin:0 auto; width:500px; position:relative;">
<div id="child" style="position:absolute; top:10px; left:10px;"></div>
</div>
This doesn't have to be the direct parent, when you set absolute positioning the element will position from the nearest ancestor with a set positioning.
这不必是直接父级,当您设置绝对定位时,元素将从最近的祖先开始定位并设置定位。
回答by Headshota
parent must have position:relative; (or some other positioning apart from static) so that it's child can be positioned absolutely relative to them.
父母必须有职位:相对;(或除静态之外的其他一些定位),以便它的孩子可以相对于它们绝对定位。
回答by Hussein
You need to give your parent div position:relative
and your child div position absolute
你需要给你的父 divposition:relative
和你的孩子 divposition absolute
Check working example at http://jsfiddle.net/remYW/
在http://jsfiddle.net/remYW/检查工作示例