1. 把一些 div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align 属性
<div class='wrapper'>
<div class='content'>我是内容</div>
</div>
.wrapper{
display: table;
width:100px;
height:100px;
}
.content{
display:table-cell;
vertical-align: middle;
}
2. 还是上面的结构 利用position absolute定位,这个方法 必须指定元素的高度
.wrapper{
position: relative;
width:100px;
height:100px;
text-align: center;
}
.content{
position: absolute;
width:100px;
height:20px;
top:50%;
margin-top:-10px;
}
3. 利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto
<div class="content"> Content here</div>
.content{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 50px;
width: 200px;
}
4. 利用translate垂直居中
.content{
position: absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
width: 100px;
height: 34px;
}
5. 单行文本的垂直居中
.content{
height:100px;
line-height:100px
}
6. 多行单行文本的垂直居中
<div class="linebox">
<span>
<p>我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,我是文字,</p>
<i>后面是文字。</i>
</span>
</div>
.linebox{
width:300px;
height:300px;
border:1px solid #ccc;
line-height: 300px;
text-align: center;
margin:0 auto;
padding:10px;
}
.linebox span{
display: inline-block;
vertical-align: middle;
}