在前端开发中,实现水平居中很容易,一般实现方式:给元素margin:0 auto;
但是垂直居中就不那么好控制了。
怎么样垂直居中呢?
这里可以用到position属性,
假设有如下结构
HTMl:
<div class="father">
<div class="child"></div>
</div>
CSS
.father{
width:500px;
height:500px;
position:relative;
background-color:green
}
.child{
position:absolute;
width:200px;
height:200px;
top:50%;/*********************这里是关键*********/
margin-top:-100px;/**************向上修正为元素的一半**********/
background-color:red;
}
这样就可以实现垂直居中。当然margin-top:-150px也可以使用css3中transform:translateY(-150px)修正,但是,css3毕竟有些许的兼容问题。