1.flex布局
<div class="flex">
<div>
<p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
<p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
</div>
</div>
.flex{
/*flex 布局*/
display: flex;
/*实现垂直居中*/
align-items: center;
/*实现水平居中*/
justify-content: center;
text-align: justify;
width:200px;
height:200px;
background: #000;
margin:0 auto;
color:#fff;
}
2.模拟表格
将容器设置为display:table,然后将子元素也就是要垂直居中显示的元素设置为display:table-cell,然后加上vertical-align:middle来实现。
<div id="wrapper">
<div id="cell">
<p>测试垂直居中效果测试垂直居中效果</p>
<p>测试垂直居中效果测试垂直居中效果</p>
</div>
</div>
#wrapper {display:table;width:300px;height:300px;background:#000;margin:0 auto;color:red;}
#cell{display:table-cell; vertical-align:middle;}
3.利用子绝父相定位方式来实现
<style>
.container{
width: 300px;
height: 300px;
position: relative;
}
.conter{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
4.利用Css3的transform,可以轻松的在未知元素的高宽的情况下实现元素的垂直居中
<style>
.container{
position: relative;
}
.conter{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
在父元素设置相对定位(position: relative;)的情况下,同时子元素设置了绝对定位(position: absolute;),此时子元素是贴着父元素左上角的。当子元素再次添加(top: 50%; left: 50%)两个属性后,这时候span才紧贴着第四象限,这时候再添加(transform: translate(-50%, -50%);),将其往左边和上面平移span自身长度的50%,子元素才在父元素里面居中。