2012-09-11 62 views
0

好吧,所以這個問題has been asked and answered很多次,但我仍然無法產生一個工作的解決方案。垂直對齊一個DIV redux

我想垂直對齊DIV中的中間任意元素。因此,鏈接到的上述問題教程說:

Specify the parent container as position:relative or position:absolute. 
Specify a fixed height on the child container. 
Set position:absolute and top:50% on the child container to move the top down to the middle of the parent. 
Set margin-top:-yy where yy is half the height of the child container to offset the item up. 

在代碼中的一個例子:

<style type="text/css"> 
    #myoutercontainer { position:relative } 
    #myinnercontainer { position:absolute; top:50%; height:10em; margin-top:-5em } 
</style> 
... 
<div id="myoutercontainer"> 
    <div id="myinnercontainer"> 
     <p>Hey look! I'm vertically centered!</p> 
     <p>How sweet is this?!</p> 
    </div> 
</div> 


除了違背截圖什麼教程顯示,this doesn't work。我改變的唯一方法是在外部DIV周圍添加邊框,以便您可以看到垂直對齊。

所有這些都會產生一個零高度的DIV,呈現爲一條直線。如果向外部DIV添加高度,則可以看到內部內容,但實際上並不實際垂直對齊內容。那麼,爲什麼這個例子沒有工作?

+0

嘿,我成功地集中了內部div,但這裏遲到了,懶得想怎麼把文本居中。 http://jsfiddle.net/HPN8e/2/ –

回答

0

我相信你的div還必須有一個指定的高度。如果您使用螢火蟲檢查#myoutercontainer div,您會發現它實際上具有13em的高度,但它們並未在給出的示例代碼中顯示。

0

Here's基於此Chris Coyer article的另一種方法。如果要將文本垂直居中放置到固定大小的div,則可以重複該過程like so。如果你想讓它對齊到右側,只需修改「text-align:center」; style for myoutercontainer。