垂直居中的div?

时间:2012-10-07 19:16:13

标签: html css centering

我试图在body(不是水平)中垂直居中。此外,我不想指定高度或类似的东西。我尝试添加一个100%高度和其他东西的包装,但无处可去。能帮我解决这个问题吗?

jsFiddle Here

 <form name="signup" class="signup" action="signup.php" style="border: 1px solid #000; ">
     <input type="text" placeholder="Email"/><br>
     <input type="text" placeholder="Username"/><br>
     <input type="password" placeholder="Password"/><br>
     <button type="submit">Next</button>
 </form>​

5 个答案:

答案 0 :(得分:48)

请参阅this edited version of your jsFiddle

基本上,只需将您的内容包装在<div class = "main"><div class = "wrapper"></div></div>中,然后添加以下CSS:

html, body {
    height: 100%;
}
.main {
    height: 100%;
    width: 100%;
    display: table;
}
.wrapper {
    display: table-cell;
    height: 100%;
    vertical-align: middle;
}

答案 1 :(得分:6)

更新:jsFiddle

&#13;
&#13;
form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%); /* IE 9 */
    -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */	    
}
&#13;
<form name="signup" class="signup" action="signup.php" style="border: 1px solid #000; ">
     <input type="text" placeholder="Email"/><br>
     <input type="text" placeholder="Username"/><br>
     <input type="password" placeholder="Password"/><br>
     <button type="submit">Next</button>
 </form>​
&#13;
&#13;
&#13;

相关:Center a div in body

答案 2 :(得分:5)

如果您有弹性箱,则无需使用display: table;

即可

代码示例:

html,
body {
  height: 100%;
  width: 100%;
}

.container {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}
<html>
  <body>
    <div class="container">
      <div class="content">
        This div will be centered
      </div>
    </div>
  </body>
</html>

钽哒!垂直和水平居中的内容div。 JSFiddle:https://jsfiddle.net/z0g0htm5/

主要来自https://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/https://css-tricks.com/snippets/css/a-guide-to-flexbox/

答案 3 :(得分:1)

这对我有用:

<强>的style.css

div {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

我找到了此代码段here

答案 4 :(得分:0)

带表warp的JSFiddle示例

在上面的解决方案中,为html&amp;提供css;带有"height: 100%"的正文,然后将表格包围在一个表格中心。

代码示例

<html>
<body>    
<table height="100%" width="100%" border="1">
    <tr>
    <td>
    <form name="signup" class="signup" action="signup.php" style="border: 1px solid #000; ">

                <input type="text" placeholder="Email"/><br>

                <input type="text" placeholder="Username"/><br>

                <input type="password" placeholder="Password"/><br>

                <button type="submit">Next</button>

            </form>
        </td>
        </tr>
</table>    
</body>
</html>