如何在窗口resize时使用jquery水平居中一个相对div?

我最初使用jquery水平居中div但是当窗口resize时它看起来很糟糕所以我想要做的是在窗口resize后使用jquery保持居中

有办法帮忙吗?

编辑

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

请查看http://hrmanagementbradford.com/gallery/

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

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

当css可以执行一行时,为什么使用jquery水平居中,当调整浏览器大小时它将保留在中心:

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

你可以把它像死神一样:

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

您可以使用

 margin: 0 auto; 

在CSS中水平居中一个块元素。

像这样:

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

做这个:

 $(window).resize(function(){ // reposition div again here })