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

编程入门 行业动态 更新时间:2024-10-14 16:25:35

统一的样式

文字水平居中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;。

更多推荐

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

本文发布于:2023-06-13 12:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1381922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:display   box   flex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!