垂直置中的幾種方法比較(純CSS)

來源:互聯網
上載者:User
方法一

<div class="table" style="height: 200px;">    <div class="table-cell">content    </div></div>.table {display:table;}.table-cell {display:table-cell; vertical-align:middle;}

優點:content 可以動態改變高度,如果你不需要支援IE7瀏覽器,這個應該是首選方案,也是W3C推薦的方案。

缺點:IE7和IE8 beta不支援。 方法二

<div class="content">Content</div>#content { position:absolute; top:50%; height:240px; margin-top:-120px; /* negative half of the height */ overflow: auto;}

優點:適用於所有瀏覽器。

缺點:內容地區高度固定,如果不用overflow:hidden或overflow:auto,內容顯示就會超出內容地區,看起來就不是置中了。


而使用overflow:hidden,超出的內容就會消失;使用overflow:auto則會出現捲軸。 方法三 - 不推薦使用

這個方法利用的是margin:auto的計算方法,給內容地區div#content設定一個固定高度,並且設定position:absolute;top:0; bottom:0;。因為它有固定高度,其實並不能使上下都間距為 0,因此 margin:auto; 會使它垂直置中。

<divid="content">Content </div>#content{ position:absolute; top:0; bottom:0; margin:auto; height:240px;}

優點:明顯不如第一種方法,一般不用。

缺點:IE7和IE8 beta中無效;因為內容地區高度固定,和第二種方法有相同的問題。 方法四

這個方法只能將單行文本置中。只需要簡單地把 line-height 設定為內容容器的height 值就可以使文本置中了。

<divid="content">Content </div>#content{height:100px; line-height:100px;}

優點:適用於所有瀏覽器;在文本不換行的小元素上非常有用,例如使按鈕文本或者單行文本置中。

缺點:只對文本有效(區塊層級元素無效);多行時因為line-height太高,行距會非常大;

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.