How to center text vertically in HTML using CSS only

前端 未结 5 805
醉酒成梦
醉酒成梦 2020-12-17 04:53

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.


    &         


        
相关标签:
5条回答
  • 2020-12-17 05:01

    Try this:

    .text-tag{
    
        text-align: center;
        margin-top: 25%;
    }
    

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

    0 讨论(0)
  • 2020-12-17 05:09
    <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>
    
    0 讨论(0)
  • 2020-12-17 05:11
    <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>
    
    0 讨论(0)
  • 2020-12-17 05:17

    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

    0 讨论(0)
  • 2020-12-17 05:20

    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>
    
    0 讨论(0)
提交回复
热议问题