我如何去设置一个<div>在屏幕的中心使用jQuery?


当前回答

编辑:

如果这个问题教会了我什么,那就是:不要改变已经有效的东西:)

我提供了一个(几乎)一字不差的副本,这是如何处理http://www.jakpsatweb.cz/css/css-vertical-center-solution.html -这是严重黑客的IE,但提供了一个纯CSS的方式来回答这个问题:

.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper    {#position:absolute; #top:50%;
            display:table-cell; vertical-align:middle;}
.content   {#position:relative; #top:-50%;
            margin:0 auto; width:200px; border:1px solid orange;}

小提琴:http://jsfiddle.net/S9upd/4/

我在浏览器中运行了这个,看起来很好;如果没有别的原因,我将保留下面的原始内容,以便按照CSS规范规定的保证金百分比处理。

原:

看来我要迟到了!

上面有一些评论认为这是一个CSS问题——关注点的分离。让我先说一句,CSS在这个问题上搬起石头砸自己的脚。我的意思是,这样做有多简单:

.container {
    position:absolute;
    left: 50%;
    top: 50%;
    overflow:visible;
}
.content {
    position:relative;
    margin:-50% 50% 50% -50%;
}

对吧?容器的左上角将位于屏幕的中心,如果边框为负,内容将神奇地重新出现在页面的绝对中心!http://jsfiddle.net/rJPPc/

错了!水平定位是可以的,但垂直…哦,我明白了。显然,在css中,当设置顶部边距为%时,该值总是以相对于包含块宽度的百分比计算。就像苹果和橘子一样!如果你不相信我或Mozilla doco,可以通过调整内容宽度来玩上面的小提琴,你会惊讶的。


现在,CSS是我的面包和黄油,我不打算放弃。同时,我喜欢简单的东西,所以我借用了捷克CSS大师的发现,并使其成为一个工作小提琴。长话短说,我们创建了一个表,其中vertical-align设置为中间:

<table class="super-centered"><tr><td>
    <div class="content">
        <p>I am centered like a boss!</p>
    </div>
</td></tr></table>

并且比内容的位置微调了好老距:0 auto;:

.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​

工作提琴承诺:http://jsfiddle.net/teDQ2/

其他回答

我在扩展@TonyL给出的精彩答案。我添加了Math.abs()来包装值,而且我还考虑到jQuery可能处于“无冲突”模式,例如在WordPress中。

I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.

我做的另一件事是通过缓存$(window)对象来加快速度,这样我就减少了额外的DOM遍历,并且我使用了集群CSS。

jQuery.fn.center = function ($) {
  var w = $(window);
  this.css({
    'position':'absolute',
    'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
    'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
  });
  return this;
}

要使用,你可以这样做:

jQuery(document).ready(function($){
  $('#myelem').center();
});

我喜欢添加函数到jQuery,所以这个函数会有帮助:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

现在我们可以写成:

$(element).center();

演示:小提琴(添加参数)

有很多方法可以做到。我的对象被display:none隐藏在BODY标签中,以便定位相对于BODY。在使用$ (" # object_id”),告诉(),我叫美元(“# object_id”).center ()

我使用position:absolute,因为这是可能的,特别是在一个小型移动设备上,模式窗口比设备窗口大,在这种情况下,如果定位是固定的,一些模式内容可能是不可访问的。

以下是根据其他人的回答和我的具体需求我的口味:

$.fn.center = function () {
        this.css("position","absolute");

        //use % so that modal window will adjust with browser resizing
        this.css("top","50%");
        this.css("left","50%");

        //use negative margin to center
        this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
        this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");

        //catch cases where object would be offscreen
        if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
        if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});

        return this;
    };

你可以像这样单独使用CSS居中:

工作示例

.center { 位置:绝对的; 高度:50 px; 宽度:50 px; 背景:红色; 顶部:calc(50% - 50px/2);/*高度除以2*/ 左:calc(50% - 50px/2);/*宽度除以2*/ } < div class = "中心" > < / div >

Calc()允许您在css中进行基本计算。

用于calc()的MDN文档 浏览器支持表

不需要jquery

我用这个来居中Div元素。 Css样式,

.black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}

.white_content {
    display: none;
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 16px solid orange;
    background-color: white;
    z-index:1002;
    overflow: auto;
}

开放的元素

$(document).ready(function(){
    $(".open").click(function(e){
      $(".black_overlay").fadeIn(200);
    });

});