高度百分比文字如何垂直居中

一.经常使用方式

让文字水平垂直居中一般使用的方法是:text-align: center(水平居中);line-height: 20px(垂直居中);值得注意的是line-height的值必须是固定值,即该元素的高度必须固定。html

二.引出问题

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <style>
            *{
                width: 100%;
                height: 100%;
            }
            .box{
                width: 40%;
                height: 30%;
                font-size: 24px;
                background: red;
                text-align: center;
                line-height: 100%;        (注意)
            }
    </style>
    <body>
        <div class="box">
            快让我水平垂直居中!!!
        </div>
    </body>
    </html>
复制代码

效果图: 布局

设置line-height是没用的。

三.决解方案

  1. 利用弹性布局
  2. 利用display:table-cell

display:table-cell属性指让标签元素以表格单元格的形式呈现,相似于td标签。由于单元格有一些比较特别的属性,例如元素的垂直居中对齐,关联伸缩等,咱们能够利用单元格的特性来实现功能。多行文本居中一样适用。
相关文章
相关标签/搜索