繁体   English   中英

使用jQuery将div垂直和水平居中

[英]Centering a div vertically & horizontally using jQuery

我正在使用此脚本将div水平和垂直居中。

当页面加载时,div会垂直居中,而不是水平居中,直到我调整浏览器大小为止。

我究竟做错了什么?

$(document).ready(function (){
    $(window).resize(function (){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    $(window).resize();
});

我通常使用这种“技术”:

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : -$('.className').width()/2,
        'margin-top' : -$('.className').height()/2
    });
});

更新:

我正在更新解决方案,如用户Fred K所建议,使用.outerWidth().outerHeight()获得更精确的居中。

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : -$('.className').outerWidth()/2,
        'margin-top' : -$('.className').outerHeight()/2
    });
});

jQuery文档中的一些其他说明( .outerWidth() .outerHeight() ):

  • 在某些情况下,与尺寸相关的API返回的数字(包括.outerWidth())可能是小数。 代码不应假定它是整数。 另外,当用户缩放页面时,尺寸可能不正确; 浏览器不会公开API来检测这种情况。

  • 当隐藏元素的父元素时,不能保证.outerWidth()报告的值是准确的。 要获得准确的值,应先显示父对象,然后再使用.outerWidth()。


更新2:

一个简单的更新,显示了如何在css()方法中使用this方法,以防存在更多具有相同class标签且大小不同的元素。

$(function() {
    $('.className').css({
        'position' : 'absolute',
        'left' : '50%',
        'top' : '50%',
        'margin-left' : function() {return -$(this).outerWidth()/2},
        'margin-top' : function() {return -$(this).outerHeight()/2}
    });
});

使用它来居中:

$.fn.center = function () {
   this.css("position","absolute");
   this.css("top", ( $(window).height() - this.height() ) / 2  + "px");
   this.css("left", ( $(window).width() - this.width() ) / 2 + "px");
   return this;
}

$('yourElem').center();

将处理程序代码包装在一个函数中,以便您可以在页面加载以及$(window).resize()处理程序中调用该函数

/* use as handler for resize*/
$(window).resize(adjustLayout);
/* call function in ready handler*/
$(document).ready(function(){
    adjustLayout();
    /* your other page load code here*/
})

function adjustLayout(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });

}

与您的代码段相关,您需要首先设置位置:

$(window).resize(function (){
    var $el = $('.className');
    $el.css('position', 'absolute').css({
        left: ($(window).width() - $el.width()) / 2,
        top: ($(window).height() - $el.height()) / 2
    });
});

也许您可以通过静态 CSS样式设置position属性。

基于@dimi的答案,可以更好地处理多个元素

$(".className").each(
    function () {
       $( this ).css("position","absolute");
       $( this ).css("left","50%");
       $( this ).css("margin-left", - $( this ).outerWidth()/2 );
       $( this ).css("top","50%");
       $( this ).css("margin-top", - $( this ).outerHeight()/2 );
       return this;
    }
);

我使用此JQuery.center插件将DOM元素居中。 该代码将是这样的:

$("#child").center()

先前的代码将相对于其直接父对象居中,如果您需要相对于另一个父对象居中,则它将为:

$("#child").center($("#parent"))

如果您需要其他形式的集中化,则有自定义选项。

我最近一直试图在浏览器窗口的中间放置一个框。 我在下面创建了代码。 jQuery脚本很长,因为我考虑了html和body标签的所有填充和边距(如果有人设置了它们)。 如果不关心背景,则只需设置winwidth,winheight,toppx,leftpx和“ #container”。 其余的可能会被删除。

<!DOCTYPE html>
<html>
<head>
    <title>Test of centre of container</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <style>
        html {
            background-color: #444;
            margin: 30px;
        }
        #wrapper {
            background-color: #777;
            width: 75%;
            margin: 0 auto;
            padding: 0;
        }
        #container {
            background-color: #ddd;
            border-radius: 10px;
            box-shadow: 0 0 2px #222;
            width: 200px;
            height: 100px;
            position: absolute;
            vertical-align: middle;
        }
        #extext {
            text-align: center;
            padding: 0;
        }
    </style>
</head>
<body>
    <script>
        function setDimensions() {
            var winwidth = $(window).width();
            var winheight = $(window).height();
            var htmlmv = parseInt($("html").css("margin-top")) + parseInt($("html").css("margin-bottom"));
            var htmlpv = parseInt($("html").css("padding-top")) + parseInt($("html").css("padding-bottom"));
            var htmlmh = parseInt($("html").css("margin-left")) + parseInt($("html").css("margin-right"));
            var htmlph = parseInt($("html").css("padding-left")) + parseInt($("html").css("padding-right"));
            var bodymv = parseInt($("body").css("margin-top")) + parseInt($("body").css("margin-bottom"));
            var bodypv = parseInt($("body").css("padding-top")) + parseInt($("body").css("padding-bottom"));
            var bodymh = parseInt($("body").css("margin-left")) + parseInt($("body").css("margin-right"));
            var bodyph = parseInt($("body").css("padding-left")) + parseInt($("body").css("padding-right"));
            var vspace = htmlmv + htmlpv + bodymv + bodypv;
            var hspace = htmlmh + htmlph + bodymh + bodyph;
            var wrapheight = winheight - vspace;
            var wrapwidth = winwidth - hspace;
            $("#wrapper").height(wrapheight);
            // $("#wrapper").width(wrapwidth);

            var toppx = (winheight - parseInt($("#container").css("height"))) / 2;
            var leftpx = (winwidth - parseInt($("#container").css("width"))) / 2;
            $("#container").css("top", toppx.toString() + "px");
            $("#container").css("left", leftpx.toString() + "px");
        }

        $(document).ready(function () {
            setDimensions();
        });
        $(window).resize(function () {
            setDimensions();
        });
    </script>
    <div id="wrapper">
        <div id="container">
            <p id="extext">Example text</p>
        </div>
    </div>
</body>
</html>





编辑:我在CSS Tricks网站上找到了更好的解决方案,它仅使用CSS :)。 代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>
        Test centring!
    </title>
    <style>
        body div {
            background-color: red;
            box-shadow: 0 0 15px #222;
            border-radius: 10px;
            padding: 10px;
            margin: -150px auto auto -200px;
            width: 380px;
            height: 280px;
            position: absolute;
            top: 50%;
            left: 50%;
            text-align: center;
            line-height: 140px;
        }
        body div h2 {
            color: yellow;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <div>
        <h2>
            Example text<br />
            Example Text
        </h2>
    </div>
</body>
</html>

我的班级中心的div必须水平居中,并且位置固定。 我使用以下小代码来实现它:

$(window).on('resize load', function () {
    $('.center').each(function () {
        $(this).css({
            'margin-left': ($('body').width() - $(this).width()) / 2
        });
    });
});

您也可以使用相同的策略进行水平对齐。 看一下它在加载和调整大小事件时立即处理,因此该div始终位于中间。

您可以使用该插件,使用https://github.com/tenbullstech/jquery-make-me-center非常简单

$("div.box").makemecenter();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM