为什么我的弹性项目不在中心?

jso*_*on1 5 html css css3 centering flexbox

我试图将一个红色框放在页面中间.

我已将flex容器设置为100%的高度,并且还将html,body设置为100%,并且它仍然不对齐center.

谁能帮助我理解为什么它不起作用?谢谢!

html, body {
  height: 100%;
}
.flex-container {
  display: flex;
  flex-flow: column;
  justify-content: center;
  height: 100%;
}
.box {
  flex: 0 0 100px;
  background: red;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div class='flex-container'>
    <div class='box'></div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 5

您可以用来在主轴justify-content上对齐弹性项目。

您可以用来在横轴align-items上对齐弹性项目。

由于您的弹性容器是flex-direction: column

  • 主轴是垂直的,并且
  • 横轴是水平的。

justify-content: center工作正常。

您只需要添加align-items: center.

html, body {
  height: 100%;
}
.flex-container {
  display: flex;
  flex-flow: column;
  justify-content: center;       /* centers flex items vertically, in this case */
  align-items: center; /* NEW */ /* centers flex items horizontally, in this case */
  height: 100%
}
.box {
  flex: 0 0 100px;
  background: red;
  width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div class='flex-container'>
  <div class='box'></div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是更详细的解释: