HTML中字体使用line-height依然不能垂直居中解决办法

文本水平居中,还要垂直居中,此时我们写代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #next-button{
                    height: 54px;
                text-align: center;
                color: #fff;
                background: #e2231a;
                line-height: 54px;
                font:16px "Microsoft YaHei","Hiragino Sans GB";
                cursor: pointer;
                margin: 0 auto;
                width:400px;
            }
             
        </style>
    </head>
    <body>
        <div id="next-button">下一步</div>
    </body>
</html>

在其中,我们设置了宽度、高度、背景颜色、字体以及水平与垂直居中,然而,我们却得到了这样的效果:

我们设置的文本垂直居中并没有效果。@ www.xuepai.net而我们改代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #next-button{
                width:400px;
                height: 54px;
                text-align: center;
                color: #fff;
                background: #e2231a;
                font:16px/54px "Microsoft YaHei","Hiragino Sans GB";
                cursor: pointer;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div id="next-button">下一步</div>
    </body>
</html>

的时候,就可以垂直居中。@ www.haoshilao.net原因就在于如果样式声明列表中有line-height与font,则line-height无效,必须与font一起使用。只要样式声明中没有font,就可使用line-height来设置文本的垂直居中了。

posted @ 2026-01-06 20:59  zxcva  阅读(35)  评论(0)    收藏  举报