[英]how to center a relative div horizontally using jquery on window resize?
我最初是使用jquery將div水平居中,但是當調整窗口大小時,它看起來很糟糕,所以我想做的是在調整窗口大小后,使用jquery使其居中
有什么辦法可以幫助?
編輯
伙計們,我已經成功地將其他要素置於中心,但是我現在遇到另一個問題:(
請檢查此http://hrmanagementbradford.com/gallery/
並調整窗口大小,您將看到內容放置不正確,我試圖修復此問題已有幾個小時,但找不到解決方案,請提供幫助
編輯解決! 它很復雜,我的代碼非常具體,所以在這里發布它不會有幫助:),盡管我使用jquery將其居中,但是如果我們使用css的東西,那么FutureKode的答案最適合我:)
為什么當CSS可以一行執行jquery並使其水平調整時,使用jquery將其水平居中:
div {
margin:0 auto;
width:800px
}
您可以使用
margin: 0 auto;
使塊元素在CSS中水平居中。
像這樣:
div
{
width: 400px;
margin: 0 auto;
}
您可以像這樣使它死心:
$('#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'});
});
做這個:
$(window).resize(function(){
// reposition div again here
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.