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>

在这里插入图片描述

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>

在这里插入图片描述

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>

在这里插入图片描述

总结

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

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

1)单行

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

2)多行

设置该元素 css 属性:display: table-cell; vertical-align: middle;,
还需设置该元素的父级元素 css 属性:display: table;。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值