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


当前回答

这是我的版本。看完这些例子后,我可能会改变它。

$.fn.pixels = function(property){
    return parseInt(this.css(property));
};

$.fn.center = function(){
    var w = $($w);
    return this.each(function(){
        $(this).css("position","absolute");
        $(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
        $(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
    });
};

其他回答

我想纠正一个问题。

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

以上代码在这种情况下将不起作用。height(假设用户调整屏幕大小,内容是动态的)和scrollTop() = 0,示例:

窗口。高度是600 这一点。高度是650

600 - 650 = -50  

-50 / 2 = -25

现在方框在屏幕外的中心位置为-25。

这是我的尝试。我最终在我的Lightbox克隆版本中使用了它。这种解决方案的主要优点是,即使窗口大小被调整,元素也会自动保持居中,这是这种用法的理想选择。

$.fn.center = function() {
    this.css({
        'position': 'fixed',
        'left': '50%',
        'top': '50%'
    });
    this.css({
        'margin-left': -this.outerWidth() / 2 + 'px',
        'margin-top': -this.outerHeight() / 2 + 'px'
    });

    return this;
}

通常,我只会用CSS做这个…但是既然你问你一个方法来做这个用jQuery…

下面的代码将一个div在其容器内水平和垂直地居中:

$("#target").addClass("centered-content") .wrap("<div class='center-outer-container'></div>") .wrap("<div class='center-inner-container'></div>"); body { margin : 0; background: #ccc; } .center-outer-container { position : absolute; display: table; width: 100%; height: 100%; } .center-inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding : 20px; border : 1px solid #000; } <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <div id="target">Center this!</div>

(也可以参看这把小提琴)

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

工作示例

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

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

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

我不认为有一个绝对位置将是最好的,如果你想要一个元素总是居中在页面的中间。你可能需要一个固定的元素。我发现另一个jquery定心插件使用固定定位。这叫做固定中心。