stanleyxu2005
stanleyxu2005

Reputation: 8231

How to center text vertically in HTML using CSS only

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?

Upvotes: 4

Views: 11845

Answers (5)

Amir Md Amiruzzaman
Amir Md Amiruzzaman

Reputation: 2079

<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>

Upvotes: 1

ENSATE
ENSATE

Reputation: 325

Try this:

.text-tag{

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

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

Upvotes: -2

Davide Ungari
Davide Ungari

Reputation: 1960

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>

Upvotes: 3

Bakhtiyor
Bakhtiyor

Reputation: 7318

<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>

Upvotes: 2

Matschie
Matschie

Reputation: 1247

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

Upvotes: 4

Related Questions