如何保持浮动div以窗口大小为中心(jQuery/CSS)

Jim*_*mbo 14 html javascript css jquery

是否有一种方法(没有绑定到window.resize事件)强制浮动DIV在调整浏览器窗口时重新居中?

为了帮助解释,我想像伪代码看起来像:

div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)
Run Code Online (Sandbox Code Playgroud)

UPDATE

我的查询已在下面得到解答,我想发布我的任务的最终结果 - 一个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%' });
}
Run Code Online (Sandbox Code Playgroud)

用法:

$('#mydiv').center();
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 21

如果你有一个固定大小的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 */
}
Run Code Online (Sandbox Code Playgroud)

当然,问题在于固定尺寸的元素并不理想.

  • 超级巨星,谢谢!我在下面发布的代码中使用过它(发布代码作为注释根本不起作用) (4认同)