且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使文本在HTML页面中垂直和水平居中

更新时间:2022-11-01 23:27:27

水平居中很容易 - 垂直居中在css中有点棘手,因为它不是真正支持的(除了表格单元格< td> 坏的风格布局,除非一个表真的需要 - 一个表)。但是你可以使用语义正确的html标签并应用表格显示属性。

Centering horizontally is easy - centering vertically is a bit tricky in css as it's not really supported (besides table cells <td>, which is bad style for layouting unless a table is really needed as - well - a table). But you can use semantically correct html tags and apply table display properties to it.

这是一个可能的解决方案 - 有很多方法,这里有一篇很好的文章

That's one possible solution - there are many approaches, here is a good article on that.

在你的情况下,这样的东西应该足够了:

In your case something like that should be sufficient:

<!DOCTYPE html>
<html lang="de">
    <head>
        <title>Hello World</title>
        <style>

        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            width: 100%;
        }

        body {
            display: table;
        }

        .my-block {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }
        </style>
    </head>
    <body>
    <div class="my-block">
       WORD1<br />
       WORDWORDWORDWORD2
    </div>
    </body>
</html>