How to center text vertically in HTML using CSS only

走远了吗. 提交于 2019-12-18 04:23:17

问题


I have a very simple HTML. Due to some limitations, I cannot modify the HTML content. I want to center the text vertically only using CSS.

<html>
    <head>...</head>

    <body>
        <div>Oops, the webpage is currently not available.</div>
    </body>
</html>

Note that the size of the HTML can be variable.

In addition, if the text cannot be displayed in one line, it should be broken into multiple lines.

Is it possible?


回答1:


I think vertical-align only works for content which is in a table. For your simple page you could put the content in a table instead of a div to avoid this problem.

There are some workarounds, see http://phrogz.net/css/vertical-align/index.html




回答2:


Another possible solution:

<html>
    <head>
        <title>Title</title>
        <style>
            body {height:100%}
        </style>
    </head>

    <body>
        <div style="height:100%;">
            <div style="position:relative;top:50%;text-align:center">Oops, the webpage is currently not available.</div>
        </div>
    </body>
</html>



回答3:


<html>
    <head>...
       <style type="text/css">
           div{
               width: 300px;
               height: 300px;
               border: solid blue;
               display: table-cell;
               vertical-align: middle;
           }
       </style>
    </head>

    <body>
        <div>This works fine!</div>
    </body>
</html>



回答4:


<html>
    <head>
        <style type="text/css">
            .vertical {
                margin: 0;
                background: yellow;
                position: absolute;
                top: 50%;
                left: 50%;
                margin-right: -50%;
                transform: translate(-50%, -50%) 
            }
        </style>
    </head>
    <body>
        <div class="vertical">
         Centered
        </div>
    </body>
</html>



回答5:


Try this:

.text-tag{

    text-align: center;
    margin-top: 25%;
}

And apply "text-tag" to the text you want to center.



来源:https://stackoverflow.com/questions/2943234/how-to-center-text-vertically-in-html-using-css-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!