DIV CSS 佈局教程網

用 jQuery 讓 DIV 真正置中的三種寫法
編輯:JQuery特效代碼     

「讓一個 div 在畫面上水平垂直居中」是 CSS 面試的經典題,也是很多前端初學者的第一道坎。用 jQuery 反而幾行就能搞定,以下從最精簡一路寫到最完整的插件版本。

極簡版:一行搞定

$('#myDiv').css({
  top  : '50%',
  left : '50%',
  margin: '-' + ($('#myDiv').height() / 2) + 'px 0 0 -' + ($('#myDiv').width() / 2) + 'px'
});

原理是把元素左上角移到畫面正中,再用負的 margin 把自己拉回一半的距離。這個寫法的弱點很明顯:元素尺寸必須是已知的固定值,而且 margin 的拼字順序(上 右 下 左)很容易寫錯。

簡潔版:用 outerHeight 自動算

(function($){
  $.fn.extend({
    center: function () {
      return this.each(function() {
        var top  = ($(window).height() - $(this).outerHeight()) / 2;
        var left = ($(window).width()  - $(this).outerWidth())  / 2;
        $(this).css({ position:'absolute', margin:0,
                      top : (top  > 0 ? top  : 0) + 'px',
                      left: (left > 0 ? left : 0) + 'px' });
      });
    }
  });
})(jQuery);

$('#mainDiv').center();

改用 outerHeight() 與 outerWidth() 後,元素連 border 和 padding 的實際佔用都會被算進去,不必再手動填數字。top > 0 ? top : 0 的判斷是防止元素比視窗還大時算出負值跑到畫面外。

完整插件版:可設定、可動畫

(function($){
  $.fn.extend({
    center: function (options) {
      var options = $.extend({
        inside       : window, // 以哪個元素為容器
        transition   : 0,      // 動畫毫秒數
        minX         : 0,      // 允許的最小 left
        minY         : 0,      // 允許的最小 top
        withScrolling: true,   // 是否把捲動量計入
        vertical     : true,   // 是否垂直居中
        horizontal   : true    // 是否水平居中
      }, options);

      return this.each(function() {
        var props = { position: 'absolute' };

        if (options.vertical) {
          var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
          if (options.withScrolling) top += $(options.inside).scrollTop()  || 0;
          top = (top > options.minY ? top : options.minY);
          $.extend(props, { top: top + 'px' });
        }

        if (options.horizontal) {
          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
          left = (left > options.minX ? left : options.minX);
          $.extend(props, { left: left + 'px' });
        }

        if (options.transition > 0) $(this).animate(props, options.transition);
        else                        $(this).css(props);
        return $(this);
      });
    }
  });
})(jQuery);

呼叫時還能綁上 resize,讓視窗縮放時浮動層永遠保持居中:

$(document).ready(function(){
  $('#mainDiv').center();
  $(window).bind('resize', function() {
    $('#mainDiv').center({ transition: 300 });
  });
});

但這真的是好方法嗎

坦白說,以上三種都是「用 JS 補 CSS 做不到的事」的產物,寫法本身沒問題,但在今天已經不是最佳解。現代 CSS 有兩行就能取代全部:

.parent { display: flex; align-items: center; justify-content: center; }
/* 或者 */
#myDiv { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

用 transform: translate(-50%,-50%) 尤其漂亮——它不必知道元素尺寸,也不會觸發重排,效能比 JS 每次計算好得多。若還在維護老專案,上面的 jQuery 版本仍然堪用;新專案請直接用 CSS。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved