css 文字垂直居中

如何实现?

  设置 行高(line-height) = 高度(height)

  演示:

 

<html>
<head>
    <title>演示</title>
    <style>
    .demo {
        width: 200px;
        height: 60px;
        background: yellow;
        text-align: center;
        line-height: 60px;
    }
    </style>
</head>
<body>
    <div class="demo">我居中显示了</div>
</body>
</html>

 

  效果:

 

 

 

为什么?

  行高 = 上距离 + 内容高度 + 下距离。因为上距离和下距离总是相同的,在文字内容高度不变(默认是16px)的情况下,让行高等于高度就能够让上距离和下距离平分剩余的高度,所以可以完成垂直居中。

 

 

   进一步,我们就可以得出以下结论:

  1. 如果行高等于高度,文字垂直居中。

  2. 如果行高小于高度,文字偏上。

  3. 如果行高大于高度,文字偏下。

 

posted @ 2020-04-26 22:35  Front-Here  阅读(632)  评论(0编辑  收藏  举报