【问题标题】:Centering a div vertically & horizontally using jQuery使用 jQuery 将 div 垂直和水平居中
【发布时间】:2012-12-03 22:09:03
【问题描述】:

我正在使用此脚本将我的 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();
});

【问题讨论】:

    标签: jquery centering


    【解决方案1】:

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

    $(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}
        });
    });
    

    【讨论】:

    • 这对我有用,但只有当我将 (this) 替换为 ('.classname') 时,可能是因为我将 div 居中在另一个 div 中,而 'this' 当前是窗口大小。你如何让“this”成为你正在研究的元素?
    • 如果我有多个不同尺寸的元素怎么办?
    • 这是一个很好的解决方案,如果 $(this) 不改变大小。但例如对于响应式设计元素,这是另一回事,如果它们因屏幕尺寸减小而改变尺寸,则此方法会失败。
    • 使用outerWidth()outerHeight() 确保获得中心
    • @mabi 是的,当然如果class 标记不够具体,可以在css() 方法中将函数作为参数传递以避免使用each() 方法。我将添加一个快速更新。
    【解决方案2】:

    基于@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;
        }
    );
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        我的带有类中心的 div 必须在中间水平居中,并且它的位置是固定的。我使用这个小代码来实现它:

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

        您也可以使用相同的策略进行水平对齐。看看它在加载和调整大小事件时立即处理,所以这个 div 总是在中间。

        【讨论】:

          【解决方案5】:

          我最近一直在尝试在浏览器窗口的中间放置一个框。我创建了下面的代码。 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 website 上找到了更好的解决方案,它只使用 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>
          

          【讨论】:

            【解决方案6】:

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

            $("#child").center()
            

            前面的代码将相对于其直接父级居中,如果您需要相对于另一个父级居中,它将是:

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

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

            【讨论】:

              【解决方案7】:

              与你的代码sn-p有关,需要先设置位置:

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

              也许你可以通过 static CSS 样式设置 position 属性。

              【讨论】:

                【解决方案8】:

                将处理程序代码包装在一个函数中,这样您就可以在页面加载时调用该函数以及$(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
                    });
                
                }
                

                【讨论】:

                • 这很好,但它在第一次加载页面时对我不起作用。它停留在页面的左侧。比,当我开始调整页面大小时,它会在页面中间跳转。知道为什么吗?
                • @Pavel 在 jsfiddle.net 中创建一个复制问题的演示
                • $(window).resize(adjustLayout).resize();应该可以消除上述问题。
                【解决方案9】:

                用它来居中:

                $.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();
                

                【讨论】:

                • 绝对是更好的解决方案
                猜你喜欢
                • 2015-08-29
                • 1970-01-01
                • 2015-07-21
                • 1970-01-01
                • 2011-11-24
                • 2011-09-23
                • 2011-10-25
                • 2015-09-16
                • 2012-12-16
                相关资源
                最近更新 更多