如何在不知道高度的垂直和水平中心设置div?

时间:2019-02-18 10:03:49

标签: html css

这是我在reactjs中的登录表单,我想尝试将登录表单垂直和水平设置在居中位置,width is 35% and height is unknown因此我尝试在此表单中居中设置,我使用margin : auto,但是它只设置在水平居中而不是垂直居中,该怎么做?

HTML

    <div className="login-form">
        <Input type="text" placeholder="Username" name="username" />
        <Input type="password" placeholder="Password" name="password" />
        <Button type="primary" name="submit">Log in</Button>
      </Card>
    </div>

CSS

login-form {
  width: 35%;
  margin: auto;
}

2 个答案:

答案 0 :(得分:2)

使用此技术无法将块垂直居中,仅允许水平居中 尝试使用以下CSS代码获取垂直居中和水平居中:

login-form {
 width: 35%;
 margin: auto;
 margin-top: 50vh; /*allow us to push the login-form into the half of the viewport */
 transform: translateY(-50%); 

/ 登录表单将拍摄自己身高的一半 / }

希望这对您有用 祝你好运

答案 1 :(得分:0)

有许多可能的方法。您可以在登录表单中使用容器元素作为flexbox容器:

/* Pure visual styles */
.container {
  max-width: 300px;
  min-height: 300px;
  background-color: lightgray;
}
.login-form {
  width: 35%;
  min-height: 100px;
  background-color: blue;
}

/* Centering */
.container {
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container">
  <div class="login-form"></div>
</div>

或者,您可以使用绝对定位和transform

/* Pure visual styles */
.container {
  max-width: 300px;
  min-height: 300px;
  background-color: lightgray;
}
.login-form {
  width: 35%;
  min-height: 100px;
  background-color: blue;
}

/* Centering */
.container {
  position: relative;
}
.login-form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div class="container">
  <div class="login-form"></div>
</div>