【问题标题】:Is it possible to vertical-center an element (span, div, whatever) due to the body height?由于身体高度,是否可以垂直居中元素(跨度,div,等等)?
【发布时间】:2012-06-23 16:14:05
【问题描述】:

我希望问题很清楚。

我有 DOM 的主体(应该是任何高度,考虑到驻留在窗口的用户),我想(垂直)居中一个元素(可以包含其他子元素,但这并不意味着)。

有可能吗?也许使用桌子?我想避开Js...

【问题讨论】:

标签: html css


【解决方案1】:

您需要一个适当的标记。像这样的

<html>
<body style="position:fixed; top:0px; left:0px;bottom:0px; right:0px;  margin:0px;">
    <div style='display : table; width : 100%; height : 100%'>
    <div style='display : table-row;'>
        <div style="border:solid; display : table-cell; vertical-align : middle">
            Hello
        </div>
    </div>
    </div>
</body>
</html>

Live Example(查看我对this问题的回答)

还有其他方法

<html>
    <body style='width : 100%; height : 100%'>
        <div style='position : absolute; width : 50px; height : 50px; margin : -25px 0px 0px 0px; top : 50%; border : 1px solid #000'>
        </div>
    </body>
</html>

在这里,可以避免前面方法中看到的额外 div 元素。

Live Example

【讨论】:

  • +1 有趣的是你必须做所有这些。我从来没有尝试过对身体本身这样做,显然这样做时需要做更多的工作。
  • 问题是,您需要正确的标记才能使垂直对齐工作。所以你必须模仿display : tabledisplay : table-rowdisplay : table-cell
  • 那未必是真的:jsfiddle.net/Sha6m/8 我认为让它如此困难的部分是身高:100%;
  • 嗯..有趣。你的似乎工作正常。但是我遇到了问题,在某些情况下它不会正确居中,所以我总是遵循严格的标记。
  • 顺便说一句,当 css 不是内联时,更容易阅读您的代码。 :)
【解决方案2】:

这是我使用的一个棘手的方法。注意 wrapper 给出高度,而 wrapper > div 给出宽度。

这不应该在 IE 上工作......

<html>
<head>
    <style>
    html, body {
         height: 100%; width: 100%; margin: 0; display: table;
         vertical-align: middle
    }
    #wrapper {
         display: table-cell;
         height: 100px;
         vertical-align: middle;
         width: 100%;
    }
    #wrapper > div {
          width: 50%; margin: auto;
          border: 1px solid red
    }
</style>
</head>
<body>

<div id="wrapper">
    <div class="content">
        content there...
    </div>
</div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-26
    • 2013-06-15
    • 2014-02-10
    • 2010-09-08
    • 1970-01-01
    • 2017-06-28
    • 2013-06-24
    • 1970-01-01
    相关资源
    最近更新 更多