Javascript 如何保持浮动 div 以窗口大小为中心(jQuery/CSS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2956671/
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 keep a floating div centered on window resize (jQuery/CSS)
提问by Jimbo
Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?
有没有办法(不绑定到 window.resize 事件)在调整浏览器窗口大小时强制浮动 DIV 重新居中?
To help explain, I imagine the pseudocode would look something like:
为了帮助解释,我想伪代码看起来像:
div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)
UPDATE
更新
My query having been answered below, I wanted to post the final outcome of my quest - a jQuery extension method allowing you to center any block element - hope it helps someone else too.
我的查询已在下面得到解答,我想发布我的任务的最终结果 - 一个 jQuery 扩展方法,允许您将任何块元素居中 - 希望它也能帮助其他人。
jQuery.fn.center = function() {
var container = $(window);
var top = -this.height() / 2;
var left = -this.width() / 2;
return this.css('position', 'absolute').css({ 'margin-left': left + 'px', 'margin-top': top + 'px', 'left': '50%', 'top': '50%' });
}
Usage:
用法:
$('#mydiv').center();
回答by T.J. Crowder
This is easy to do with CSS if you have a fixed-size div:
如果你有一个固定大小的 div,这很容易用 CSS 实现:
.keepcentered {
position: absolute;
left: 50%; /* Start with top left in the center */
top: 50%;
width: 200px; /* The fixed width... */
height: 100px; /* ...and height */
margin-left: -100px; /* Shift over half the width */
margin-top: -50px; /* Shift up half the height */
border: 1px solid black; /* Just for demo */
}
The problem, of course, is that fixed-size elements aren't ideal.
当然,问题在于固定大小的元素并不理想。
回答by Bug Magnet
The simplest way would be with the following CSS code:
最简单的方法是使用以下 CSS 代码:
#floating-div {
width: 50%;
border: 1px solid gray;
margin: 0 auto;
}
The key line of CSS code above is the "margin: 0 auto;" which tells the browser to automatically set the left/right margins to keep the div centered on the page, even when you resize the browser window.
上面 CSS 代码的关键行是“margin: 0 auto;” 它告诉浏览器自动设置左/右边距以保持 div 在页面上居中,即使您调整浏览器窗口的大小也是如此。
回答by ólafur Waage
Try this little articleabout Horizontal and Vertical centering. It is a little old and has a few hacks but you should be able to work out some test code from it.

