2013-04-18 62 views
8

這就是我的代碼的樣子。垂直中心ul div

HTML

<div id="container"> 
    <ul> 
     <li>...</li> 
     <li>...</li> 
     <li>...</li> 
    </ul> 
</div> 

CSS

#container { 
    width: 584px; 
    height: 50px; 
    position: relative; 
    overflow: hidden; 
} 

#container ul { 
    position: absolute; 
    margin: 0; 
    padding: 0; 
    width: 3504px; 
} 

#container ul li { 
    width: 584px; 
    float: left; 
    margin: 0; 
    padding: 0; 
    overflow: hidden; 
} 

正如標題所說,我要垂直居中UL的DIV中。我無法更改上面的CSS規則,因爲。我一直在使用Google搜索解決方案,並試圖找到一種方法,但一切似乎都與我已有的規則相沖突。

任何想法如何做到這一點?

它會幫助,而不是#container div我用一行和一列的表?

+0

如果您事先知道元素高度(或使用JavaScript進行測量),則只能使用絕對定位。 – CBroe

+0

我可以做到這一點。你能給我多一些細節嗎? – Banana

+0

嘗試添加:auto;到你的邊際:0; – DiederikEEn

回答

0

如果你可以添加jQuery庫,你可以試試這個,

$(document).ready(function(){ 

    // Remove li float 
    $("#container ul li").css("float", "none"); 

    // Get the full height of the UL 
    var ulheight = $("#container ul li")[0].scrollHeight; 

    // Based on the height of the container being 50px you can position the UL accordingly 
    var pushdown = (50-ulheight)/2; 
    $("#container ul li").css("top", pushdown); 

}); 
+0

爲什麼要去掉浮子? – FixMaker

+0

爲了排除故障。我會嘗試讓裸骨解決方案在添加任何可能影響定位的其他任何東西之前先工作。既然有人說CSS不能被修改,那麼你可以通過jQuery刪除它。 – Rob

+0

我的意思是說我需要CSS是出於其他原因,而不是幾乎不可能將其刪除:D – Banana

3

「圍繞」一個div或其他容器縱向在CSS相當棘手,這是你的選擇。

你知道你的容器

的高度,如果你知道容器的高度,你可以做到以下幾點:

#container { 
    position: absolute; 
    top: 50%; 
    margin-top: -half_of_container_height_here; 
} 

所以我們基本上是放在中間,然後抵消它使用負值的餘量等於高度的一半。你的父容器需要有position: relative

你不知道你的容器

的確切高度在這種情況下,你需要使用JavaScript和計算適當的利潤率(不幸的是你不能使用margin-top: auto或類似的東西)。

More info here

+1

我盡我所能來說明爲什麼'margin-top'不能'自動'[這裏](http://stackoverflow.com/a/12417336/1081234) - 以及更爲優雅的居中內容方式垂直比使用絕對定位:) –

8

請使用將來的搜索功能。完整的答案解釋爲here;這是您的方案的代碼:

.container { 
    display: table; 
    height: 100%; 
    position: absolute; 
    overflow: hidden; 
    width: 100%;} 
.helper { 
    #position: absolute; /*a variation of an "lte ie7" hack*/ 
    #top: 50%; 
    display: table-cell; 
    vertical-align: middle;} 
ul{ 
    #position: relative; 
    #top: -50%; 
    margin:0 auto; 
    width:200px;} 

三個要素必須被嵌套像這樣:

<div class="container"> 
    <div class="helper"> 
    <ul><!--stuff--></ul> 
    </div> 
</div> 

http://jsfiddle.net/ovfiddle/yVAW9/

+6

難道你不覺得我已經在尋找答案嗎?你的方式行不通。 – Banana

+0

@Banana我知道這是一個古老的問題,但你使用的是什麼瀏覽器? –

+0

經過大量研究,我確定此方法適用於Opera,IE8 +,Firefox,Chrome和Safari。 –

-1

現在你可以讓父容器顯示:彎曲和align-項目:中心。這應該工作。儘管舊版瀏覽器不支持flexbox屬性。