2009-12-23 46 views
10
<div class="preview"> 
    <span class="center">This will be centered</div> 
</div> 

預覽具有固定寬度(120x120),但跨度可能包含任何內容(圖像,文本)。我該如何居中對齊垂直水平使用jQuery?我查了一些片段,但它們都將元素集中在「身體」而不是另一個元素。如果可能,我想避免使用「插件」。元素中的居中元素(jQuery)

非常感謝!

回答

4

既然你不介意使用jQuery,您可以使用Center Element Plugin

這是因爲這樣做一樣簡單:

$(".preview").center(); 
+1

鏈接中斷 –

3

既然你提到你正在使用jQuery,我假設你想通過javascript來做到這一點。您可以使用Jquery將樣式添加到DOM中的元素。您可以使用

http://docs.jquery.com/CSS/css#properties

$(.center).css({'display' : 'block', 'text-align' : 'center'}); 

根據不同的元素,你可能能夠居中,而不必使用文本對齊:中心如果邊距爲

margin: 0 auto 0 auto 

這將頂部和底部的邊距設置爲零,並在左側和右側自動設置,這可用於將塊元素居中放置在另一個塊元素內部。

要在jQuery的垂直中心的元素,你可以使用這個

http://cool-javascripts.com/jquery/vertical-alignment-of-contents-inside-an-element-using-jquery.html

function ($) { 
    $.fn.vAlign = function(container) { 
     return this.each(function(i){ 
    if(container == null) { 
     container = 'div'; 
    } 
    var paddingPx = 10; //change this value as you need (It is the extra height for the parent element) 
    $(this).html("<" + container + ">" + $(this).html() + "</" + container + ">"); 
    var el = $(this).children(container + ":first"); 
    var elh = $(el).height(); //new element height 
    var ph = $(this).height(); //parent height 
    if(elh > ph) { //if new element height is larger apply this to parent 
     $(this).height(elh + paddingPx); 
     ph = elh + paddingPx; 
    } 
    var nh = (ph - elh)/2; //new margin to apply 
    $(el).css('margin-top', nh); 
     }); 
    }; 
})(jQuery); 
2

您只能使用CSS lution使用顯示(忽略IE)

<div class="preview" style="display:table-cell;vertical-align:middle;text-align:center;margin:0 auto"> <span class="center">This will be centered</div> </div> :塊也將工作,但僅用於水平取向,垂直取向或者你將需要仿真的表格按照上面的代碼或可替代地使用JavaScript。

14

最新的jQuery UI有一個位置分量:

$("#myDialog").position({ 
    my: "center", 
    at: "center", 
    of: window 
}); 

文件:http://jqueryui.com/demos/position/
得到:http://jqueryui.com/download

+3

我不知道爲什麼這是-1。這正是我正在尋找的。超級簡單!希望我早點知道ui.position!感謝雨果。 – mrbinky3000

+0

他使用Jquery,而不是Jquery UI。增加Jquery UI的權重對於簡單居中來說是不合理的。 –

+0

android.nick - 他具體說他沒有使用jQuery UI嗎? +1這對我來說很好,已經使用jquery ui,並且正在與另一個無法正常工作的中心庫玩弄。感謝Hugo – grantk

0

你可以添加自己的功能jQuery的:

// Centers on div 
jQuery.fn.center = function (div) { 
this.css("position", "absolute"); 

var position = div.position(); 
this.css("top", Math.max(0, ((div.height() - this.outerHeight())/2) + position.top) + "px"); 

this.css("left", Math.max(0, ((div.width() - this.outerWidth())/2) + position.left) + "px"); 
return this; 
}; 

用途:

$('#ajxload').center($('#mapWrapper')).show(); 

好像從代碼的概念在Using jQuery to center a DIV on the screen