如何将div对准身体的垂直中心?

时间:2018-09-22 22:35:38

标签: html css

我需要将容器在身体的中央和中部对齐。 如果我在页面顶部添加margin-top,则会在容器div上方添加一个空白,并将背景图像也向下移动。 我希望所有内容都以百分比表示。

body {
  margin: 0px;
  height: 100%;
  background-image: url("../Images/LogIn/Background.jpg");
  background-size: 100% 100%;
}

html {
  height: 100%;
}

.Container {
  margin: auto;
  width: 60%;
  height: 80%;
  background-color: white;
  border-radius: 20px;
}
<div class="Container">
</div>

2 个答案:

答案 0 :(得分:1)

Put the following styles on the bottom to align your child div in the center:

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

答案 1 :(得分:-1)

  .container{
    margin:auto;
    width: 50%
  }

Any container with a width and relative position when styled with margin auto will automatically center inside a relatively positioned parent div (like body) - if it has content.

<style>
  .container{
    margin:auto;
    width: 50%;
    background-color: grey;
  }
</style>
<body>
  <div class="container">
    <p> text </p>
  </div>
</body>

Also as a sidenote, you should avoid styling the body at all.