垂直居中的div?

Hun*_*ell 20 html css centering

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

jsFiddle在这里

 <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>?
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 50

查看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;
}
Run Code Online (Sandbox Code Playgroud)


ant*_*ove 8

更新:jsFiddle

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 */	    
}
Run Code Online (Sandbox Code Playgroud)
<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>?
Run Code Online (Sandbox Code Playgroud)

相关:将div放在体内


小智 6

如果您有可用的flexbox,则可以不使用而执行此操作 display: table;

代码示例:

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

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

当当!垂直和水平居中的内容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/