天天看点

display:box、display:flex实现多行文本垂直居中

统一的样式

文字水平居中

text-align: center;

.box{
    height: 200px;
    width: 200px;
    background-color: #DDDDDD;
    text-align: center;
    margin: 20px; 
    padding: 0 20px;
}      

1、单行文本垂直居中

设置行高

line-height

和父元素相同

<style>
    .box-sigle{
        line-height: 200px;
    }  
</style>
    
<h2>单行</h2>
<div class="box box-sigle">
    <p>单行文本</p>
</div>      
display:box、display:flex实现多行文本垂直居中

2、多行文本垂直居中table

使用

display: table;

垂直居中

<style>
    .box-more-table{
        display: table;
    }

    .box-more-table p{
        display: table-cell;
        vertical-align: middle;
    }
</style>

<h2>多行 table</h2>
<div class="box box-more-table">
    <p>多行文本, 多行文本, 多行文本, 多行文本, 多行文本, 多行文本</p>
</div>      
display:box、display:flex实现多行文本垂直居中

3、多行文本垂直居中flex

display: flex;

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

<h2>多行 flex</h2>
<div class="box box-more-flex">
    <p>多行文本, 多行文本, 多行文本, 多行文本, 多行文本, 多行文本</p>
</div>      
display:box、display:flex实现多行文本垂直居中

总结

1、块元素垂直居中问题采用 flex 解决。

2、行内元素垂直居中问题解决如下:

1)单行

该元素 css 属性 line-height 的值与该元素的父级元素 css 属性 height 一致即可。

2)多行

设置该元素 css 属性:display: table-cell; vertical-align: middle;,

还需设置该元素的父级元素 css 属性:display: table;。