方法一
这个方法吧一些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;
}