Html 如何使绝对定位的元素与页面的其余部分一起移动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7706177/
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
How to make absolute positioned elements move with the rest of the page?
提问by roozbubu
When I absolute position an object, it is stuck there. When you resize the browser window, it stays there while the other objects slide around, thus killing the whole point.
当我绝对定位一个对象时,它会卡在那里。当您调整浏览器窗口的大小时,它会停留在那里,而其他对象则四处滑动,从而消除了整个点。
Now this is only for me. Obviously it works on normal websites, such as the one your on right now. when you resize the window everything moves around and stays in its overall template.
现在这仅适用于我。显然它适用于普通网站,例如您现在所在的网站。当您调整窗口大小时,所有内容都会移动并保留在其整体模板中。
How can I achieve this with absolute positioning?
如何通过绝对定位实现这一目标?
回答by Hussein
You need to put the absolutely positioned div inside a relatively position div. Anytime the relatively positioned div moves, the absolute positioned div will also move with it.
您需要将绝对定位的 div 放在相对位置的 div 中。任何时候相对定位的 div 移动,绝对定位的 div 也会随之移动。
<div class="relative" >
<div class="absolute">absolute</div>
</div>
.relative{
position:relative;
top:100px;
left:100px;
width:500px;
height:500px;
background:blue;
}
.absolute{
position:absolute;
width:100px;
height:100px;
background:red;
top:30px;
left:50px;
}
Check working example at http://jsfiddle.net/w2EMu/
在http://jsfiddle.net/w2EMu/检查工作示例
回答by styrr
The best solution would be to avoid absolute positioning. But if you use it and want to reposition your absolute object you could register a resize method. E.g. jQuery.resize()and reposition it yourself. If you are not using jQuery you have to use document.addEventListenerand document.attachEvent.
最好的解决方案是避免绝对定位。但是如果你使用它并想要重新定位你的绝对对象,你可以注册一个 resize 方法。例如jQuery.resize()并自己重新定位。如果您不使用 jQuery,则必须使用document.addEventListener和document.attachEvent。