css實現垂直居中的3種方法
方法一
這個方法吧一些div的顯示方式設定為表格,因此我們可以使用表格的vertical-align property屬性
html:
<div id="wrapper">
<div id="cell">
<div class="content">Content goes 你好</div>
</div>
</div>
css:
#wrapper{
display:table;
}
#cell{
display:table-cell;
vertical-align:middle;
}
缺點:相容到IE8以上版本才行
方法二:
使用絕對定位的div,把他的top設定為50%,margin-top設定為負本身高度的一半。
<div class="content">我要居中</div>
#content{
position:absolute;
top:50%;
height:240px;
margin-top:-120px;
}
優點:適用於所有的瀏覽器
缺點:沒有足夠的空間,centent會消失
方法三:
在content元素外插入一個父元素div。設定div height:50%;margin-top:-content的height
content清楚浮動,並顯示中間;
html:
<div id="floater">
<div id="content">我在中間了</div>
</div>
css:
#floater{
float:left;
height:50%;
margin-bottom:-120px;
}
#content{
clear:both;
height:240px;
position:relative;
}