利用 CSS 來實現對象的垂直置中有許多不同的方法,比較難的是選擇那個正確的方法。我下面說明一下我看到的好的方法和怎麼來建立一個好的置中網站。
使用 CSS 實現垂直置中並不容易。有些方法在一些瀏覽器中無效。下面我們看一下使對象垂直集中的5種不同方法,以及它們各自的優缺點。(可以看看測試頁面,有簡短解釋。)
方法一
這個方法把一些 div 的顯示方式設定為表格,因此我們可以使用表格的 vertical-align property 屬性。
<div id="wrapper">
<div id="cell">
<div class="content">
Content goes here</div>
</div>
</div>
#wrapper {display:table;}
#cell {display:table-cell; vertical-align:middle;}
優點:
content 可以動態改變高度(不需在 CSS 中定義)。當 wrapper 裡沒有足夠空間時, content 不會被截斷
缺點:
Internet Explorer(甚至 IE8 beta)中無效,許多嵌套標籤(其實沒那麼糟糕,另一個專題)
方法二:
這個方法使用絕對位置的 div,把它的 top 設定為 50%,top margin 設定為負的 content 高度。這意味著對象必須在 CSS 中指定固定的高度。
因為有固定高度,或許你想給 content 指定 overflow:auto,這樣如果 content 太多的話,就會出現捲軸,以免content 溢出。
<div class="content">
Content goes here</div>
#content {
position:absolute;
top:50%;
height:240px;
margin-top:-120px; /* negative half of the height */
}
優點:
適用於所有瀏覽器
不需要嵌套標籤
缺點:
沒有足夠空間時,content 會消失(類似div 在 body 內,當使用者縮小瀏覽器視窗,捲軸不出現的情況)
方法三
這種方法,在 content 元素外插入一個 div。設定此 div height:50%; margin-bottom:-contentheight;。
content 清除浮動,並顯示在中間。
<div id="floater"></div>
<div id="content">
Content here
</div>
#floater {float:left; height:50%; margin-bottom:-120px;}
#content {clear:both; height:240px; position:relative;}
優點:
適用於所有瀏覽器
沒有足夠空間時(例如:視窗縮小) content 不會被截斷,捲軸出現
缺點:
唯一我能想到的就是需要額外的空元素了(也沒那麼糟,又是另外一個話題)
方法四
這個方法使用了一個 position:absolute,有固定寬度和高度的 div。這個 div 被設定為 top:0; bottom:0;。但是因為它有固定高度,其實並不能和上下都間距為 0,因此 margin:auto; 會使它置中。使用 margin:auto;使區塊層級元素垂直置中是很簡單的。
<div id="content">
Content here</div>
#content {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
height:240px;
width:70%;