对齐项目:居中;没有按预期工作

align-items:center; not working as intended

我刚刚阅读了 David 的文章 HERE 并决定尝试一下 flexbox,所以我自己做了以下示例:

<div class="wrpr">

        <div></div>
        <div></div>
        <div></div>
        <div></div>

</div>

CSS

.wrpr {
    display: flex;
    border: 5px solid tomato;
    height: 300px;
    align-items:center;
    flex-wrap:wrap;
}

.wrpr div {
    background: #eee;
    height: 50px;
    width: 49%;
    margin: 0 .5%;
}

.wrpr div:nth-child(odd) {
    background: #727272;
}

FIDDLE HERE

现在令人讨厌的部分是 4 个 div 并不完全居中,而是间隔开。为什么会这样?

我认为这是一个典型的新手问题,对于迁移到 flexbox 的人来说,但我真的找不到解决这个问题的方法。

任何人都可以帮助我理解为什么 align-items:center; 没有按预期工作吗?

您需要使用align-content来控制multi-line间距。 align-items 仅供 single-line 使用。在您的代码中添加一行:

.wrpr {
  display: flex;
  border: 5px solid tomato;
  height: 300px;
  align-items: center;
  align-content: center; /* new */
  flex-wrap: wrap;
}

DEMO

align-content

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container. (emphasis mine)