为什么我的弹性项目没有居中对齐?

Why isn't my flex item aligning in the center?

我正试图将一个红色框置于页面中间。

我已经将 flex 容器的高度设置为 100%,并且还将 html,body 设置为 100%,但它仍然没有居中对齐。

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

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;
}
<div class='flex-container'>
    <div class='box'></div>
</div>

您使用 justify-content 主轴 上对齐弹性项目。

您使用 align-items 横轴 上对齐弹性项目。

因为你的 flex 容器是 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;
}
<div class='flex-container'>
  <div class='box'></div>
</div>

这里有更详细的解释:

您需要将 align-items 添加到 .flex-container

align-items: center;

示例见此处https://jsfiddle.net/x9gyheo6/1/