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


当前回答

我想纠正一个问题。

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

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

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

600 - 650 = -50  

-50 / 2 = -25

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

其他回答

我喜欢添加函数到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();

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

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

我更新了托尼的答案 这是他的答案的修改版本,我现在虔诚地使用。我想我会分享它,因为它为你可能有的各种情况增加了更多的功能,比如不同类型的位置,或者只想要水平/垂直居中,而不是两者都要。

center.js:

// We add a pos parameter so we can specify which position type we want

// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
    this.css("position", pos);
    this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
    return this;
}

// Center it vertically only
jQuery.fn.centerVer = function (pos) {
    this.css("position", pos);
    this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
    return this;
}

在我的<head>:

<script src="scripts/center.js"></script>

用法示例:

$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")

$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")

$("#example5").center("absolute")
$("#example6").center("fixed")

它适用于任何定位类型,可以轻松地在整个网站中使用,也可以轻松地移植到您创建的任何其他网站。没有更多的恼人的工作区,为中心的东西正确。

希望这是有用的人在那里!享受。

我将使用jQuery UI位置函数。

见工作演示。

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>

如果我有一个id“test”的div居中,那么下面的脚本将在文档准备的窗口中居中div。(位置选项中“my”和“at”的默认值为“center”)

<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>

CSS解决方案 只有两行

它集中你的内部div水平和垂直。

#outer{
  display: flex;
}
#inner{
  margin: auto;
}

对于仅水平对齐,更改

margin: 0 auto;

对于垂直方向,改变

margin: auto 0;