display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7就除外了。
<div class="box box1"> <span>垂直居中</span> </div> .box1{ display: table-cell; vertical-align: middle; text-align: center; }
注意 :此属性不能与 float:left 或是 position:absolute 一起使用。对margin值无反应,响应padding值。
方法二: display:flex
.box2{ display: flex; justify-content:center; align-items:center; }
方法三: translate
通过translate来实现移位。.box3 span{
position: absolute;
top:50%;
left:50%;
width:100%;
transform:translate(-50%,-50%);
text-align: center;
}
方法四:display:flex 和 margin:auto
.box4{
display: flex;
text-align: center;
}
.box4 span{
margin: auto;
}
每一种办法都不难理解,而且在移动端兼容性没有问题。