利用 CSS 來(lái)實(shí)現(xiàn)對(duì)象的垂直居中有許多不同的方法,比較難的是選擇那個(gè)正確的方法
使用 CSS 實(shí)現(xiàn)垂直居中并不容易
方法一
這個(gè)方法把一些 div 的顯示方式設(shè)置為表格
<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;}
優(yōu)點(diǎn):
content 可以動(dòng)態(tài)改變高度(不需在 CSS 中定義)
缺點(diǎn):
Internet Explorer(甚至 IE8 beta)中無(wú)效
方法二:
這個(gè)方法使用絕對(duì)定位的 div
因?yàn)橛泄潭ǜ叨龋蛟S你想給 content 指定 overflow:auto
,這樣如果 content 太多的話,就會(huì)出現(xiàn)滾動(dòng)條,以免content 溢出。<div class="content">
Content goes here</div>
#content {
position:absolute;
top:50%;
height:240px;
margin-top:-120px; /* negative half of the height */
}
優(yōu)點(diǎn):
適用于所有瀏覽器
不需要嵌套標(biāo)簽
缺點(diǎn):
沒(méi)有足夠空間時(shí),content 會(huì)消失(類(lèi)似div 在 body 內(nèi)
,當(dāng)用戶(hù)縮小瀏覽器窗口,滾動(dòng)條不出現(xiàn)的情況)