单行/多行文字垂直居中

转自:https://www.cnblogs.com/moqiutao/p/4807792.html

一、行高(line-height)法
如果要垂直居中的只有一行或几个文字,那它的制作最为简单,只要让文字的行高和容器的高度相同即可,比如:

<p style="border:1px solid red;width:600px;height:100px;line-height: 100px;">几个文字或者一行文字的居中对齐 方法:行高与容器高度相同</p>

在这里插入图片描述
二、内边距(padding)法
另一种方法和行高法很相似,它同样适合一行或几行文字垂直居中,原理就是利用padding将内容垂直居中,比如:

<p style="border:1px solid red;width:300px;height:auto;padding:20px 0px;">一行文字或者几行文字的居中对齐 方法:padding</p>

在这里插入图片描述
三、模拟表格法
将容器设置为display:table,然后将子元素也就是要垂直居中显示的元素设置为display:table-cell,然后加上vertical-align:middle来实现。

<div style="display:table;border:1px solid red;width:100px;height:100px;text-align:center;">
    <p style="display:table-cell;vertical-align:middle;">模拟表格法</p>
</div>

在这里插入图片描述
四、CSS3的transform来实现

<div style="border:1px solid red;width:100px;height:100px;">
    <p style="position: relative;top:50%;transform:translateY(-50%);margin:0; ">transform 法  垂直居中</p>
</div>

在这里插入图片描述

<div style="border:1px solid red;width:200px;height:100px;">
    <p style="position: relative;left:50%;transform:translateX(-50%);margin:0; ">transform法 水平居中,(无效)</p>
</div>

在这里插入图片描述
五、css3的box方法实现水平垂直居中

<div class="center">
    <div class="text">
        <p>box法</p>
        <p>我是多行文字</p>
        <p>我是多行文字</p>
        <p>我是多行文字</p>
    </div>
</div>
.center {
    width: 300px;height: 200px;border: 1px solid red;
    display: -webkit-box;-webkit-box-orient: horizontal;-webkit-box-pack: center;-webkit-box-align: center;
    display: -moz-box;-moz-box-orient: horizontal;-moz-box-pack: center;-moz-box-align: center;
    display: -o-box;-o-box-orient: horizontal;-o-box-pack: center;-o-box-align: center;
    display: -ms-box;-ms-box-orient: horizontal;-ms-box-pack: center;-ms-box-align: center;
    display: box;box-orient: horizontal;box-pack: center;box-align: center;
}

在这里插入图片描述
六、flex布局

<div class="flex">
    <div>
        <p>flex 布局</p>
        <p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
        <p>我是多行文字我是多行文字我是多行文字我是多行文字</p>
    </div>
</div>
.flex{
    display: flex;
    /*实现垂直居中*/
    align-items: center;
    /*实现水平居中*/
    justify-content: center;
    text-align: justify;width:200px;height:200px;border: 1px solid red;
}

猜你喜欢

转载自blog.csdn.net/weixin_42645716/article/details/87716547