如何在窗口调整大小时使用jquery水平居中相对div?

时间:2011-04-15 15:15:33

标签: javascript jquery

我最初使用jquery水平居中div但是当窗口调整大小时它看起来很糟糕所以我想做的是在调整窗口大小后使用jquery使其居中

有办法提供帮助吗?

修改

我已经成功地将其他元素集中在一起,但我现在有另一个问题:(

请检查一下 http://hrmanagementbradford.com/gallery/

并调整窗口大小,你会看到内容没有正确定位,我试图解决这个问题几个小时但是找不到解决方案请帮忙解决这个问题

修改 解决了!它很复杂,我的代码非常具体,所以在这里发布将无济于事:) 和 虽然我使用jquery来集中它但是如果我们使用css那么FutureKode的答案最适合我:)

4 个答案:

答案 0 :(得分:3)

为什么你使用jquery水平居中当css可以做到一行时它会在浏览器调整大小时保持在中心位置:

div {
margin:0 auto;
width:800px
}

答案 1 :(得分:2)

您可以使用

margin: 0 auto;

将块元素水平居中于CSS。

像这样:

div 
{
   width: 400px;
   margin: 0 auto;
}

答案 2 :(得分:2)

你可以像以下那样以死神为中心:

$('#elementID').css({
  position:'absolute',
  top:'50%',
  left:'50%',
  width:'600px',                 // adjust width
  height:'300px',                // adjust height
  zIndex:1000,
  marginTop:'-150px'             // half of height
  marginLeft:'-300px'            // half of width
});

请注意,元素将出现在中心但滚动时不会移动。如果您希望将其显示在中心,则需要将position设置为fixed。但是,这在IE6中不起作用。所以你的决定是:)


您还可以创建快速简单的jQuery插件:

(function($){
    $.fn.centerIt = function(settings){

        var opts = $.extend({}, $.fn.centerIt.defaults, settings);

        return this.each(function(settings){
          var options = $.extend({}, opts, $(this).data());
          var $this = $(this);

          $this.css({
            position:options.position,
            top:'50%',
            left:'50%',
            width:options.width,                 // adjust width
            height:options.height,               // adjust height
            zIndex:1000,
            marginTop:parseInt((options.height / 2), 10) + 'px'  // half of height
            marginLeft:parseInt((options.width / 2), 10) + 'px'  // half of height
          });

        });
    }

    // plugin defaults - added as a property on our plugin function
    $.fn.centerIt.defaults = {
      width: '600px',
      height: '600px',
      position:'absolute'
    }

})(jQuery);

后来就像使用它一样:

$('#elementId').centerIt({width:'400px', height:'200px'});

要在调整窗口大小时将其居中,您可以使用resize事件,以防它不像这样居中:

$(window).resize(function(){
  $('#elementId').centerIt({width:'400px', height:'200px'});
});

答案 3 :(得分:0)

这样做:

$(window).resize(function(){

   // reposition div again here

})
相关问题