![](/img/trans.png)
[英]How do I center a div in the middle of the page using jQuery and keep it centered when window is re-sized?
[英]How do I keep a div in the center of the page?
我正在使用jQuery创建一个“对话框”,它应该弹出页面顶部和页面中心(垂直和水平)。 我应该如何让它保持在页面的中心(即使用户调整大小或滚动?)
我会用
position: fixed;
top: 50%;
left: 50%;
margin-left: -(dialogwidth/2);
margin-top: -(dialogheight/2);
但是使用此解决方案并且浏览器视口大小小于对话框,对话框的部分将无法在顶部和左侧访问,因为它们位于视口之外。 所以你必须决定它是否适合你的对话框大小。
(CSS现在还不知道如何计算。所以那里的小数学必须由你完成。因此你的对话必须是一个你必须知道的固定大小。)
编辑:
哦,是的,如果你也想为IE6提供对话框,你应该这样做:
#dialog { position: absolute; }
#dialog[id] { position: fixed; }
由于IE6不具备固定位置且不具备属性选择器,因此IE6将是唯一将位置设置为绝对位置的人。 (这只会影响滚动行为。绝对停留在页面中的位置,并固定在浏览器中的位置。其余部分类似。)
#mydiv {
background-color:#F3F3F3;
border:1px solid #CCCCCC;
height:18em;
left:50%;
margin-left:-15em;
margin-top:-9em;
position:absolute;
top:50%;
width:30em;
}
这是他们使用的CSS,我已经在多个浏览器中测试过它。
您会注意到左边距是负宽度的一半而上边距是负高度的一半。 这样可以或多或少地保持定心,将其绝对定位在顶部和左侧的50%处。
要将div水平放在中间,我总是把margin:0 auto。 但它不能是浮动元素,在IE中我总是需要放置div然后给它属性text-align:center,以便内部div水平居中。
如果您知道元素的偏移尺寸(宽度/高度+填充),则可以使用此CSS:
elementContainerSelector {
position: fixed; /* You'll of course need to handle browsers that don't support fixed positioning */
top: 0;
left: 0;
width: 100%;
height: 100%;
}
elementSelector {
position: absolute;
top: 50%;
left: 50%;
margin: -[half of offset height]px 0 0 -[half of offset width]px;
}
Hurix的答案也有效,并且还要记住该答案中的警告。
保持边距左:自动和边距:自动
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.