【问题标题】:How to center text vertically in HTML using CSS only如何仅使用 CSS 在 HTML 中垂直居中文本
【发布时间】:2011-02-25 23:01:41
【问题描述】:

我有一个非常简单的 HTML。由于某些限制,我无法修改 HTML 内容。我只想使用 CSS 将文本垂直居中。

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

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

请注意,HTML 的大小是可变的。

另外,如果文字不能在一行显示,应该分成多行。

有可能吗?

【问题讨论】:

    标签: html css text center


    【解决方案1】:

    我认为垂直对齐仅适用于表格中的内容。对于您的简单页面,您可以将内容放在表格而不是 div 中以避免此问题。

    有一些解决方法,请参阅http://phrogz.net/css/vertical-align/index.html

    【讨论】:

    • CSS 的美丽新世界。你必须使用position: absoluteline-height 来做一些复杂的事情,比如垂直对齐一些内容。 (不是批评你@matschie,只是不理解制定这个标准的委员会在想什么
    • 确实是 IE 的错,否则使用 display: table 可以正常工作。
    • "line-height" 实际上有问题。如果文本太长,则其余部分超出可见区域。反正我已经放弃了。我用一张桌子代替。
    • Pekka 我完全同意你的看法,这些解决方案并不好,但我现在真的想不出别的了。
    【解决方案2】:

    另一种可能的解决方案:

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

      【讨论】:

      • 可以跳过宽度、高度、边框属性。它们仅用于直观地显示任务。
      • 虽然 IE table-cell。
      【解决方案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】:

        试试这个:

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

        并将“text-tag”应用于要居中的文本。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-22
          • 2012-02-10
          • 2015-12-03
          • 2010-11-01
          • 2013-02-14
          相关资源
          最近更新 更多