css文字垂直居中

384 阅读1分钟

css文字垂直居中方案汇总

使用伪类实现

<div class='father'>
   <div class="son">这是要居中的文字</div>
</div>
<style>
.son{
    height: 50%;
    background: blue;
    color: #fff;
}

.son::before{
    display: inline-block;
    content: "";
    height: 100%;
    vertical-align: middle;
}
</style>

使用flex布局实现

限制: son的高度只能是内容高度,不能是100%[这个实现的实际是son这个元素的居中]

<div class='father'>
   <div class="son">这是要居中的文字</div>
</div>

<style>
.father{
    display:flex;
    align-items: center;
}
</style>

使用line-height实现

限制: 必须是定高(像百分比的高度就无效)

<div style="height:30px;line-height:30px;">这是要居中的文字</div>