弹性项目宽度 flex-direction: column and margin: 0 auto

Flex item width flex-direction: column and margin: 0 auto

为什么 flex item A 设置为 margin: 0 auto 时不占用容器的整个宽度?

jsfiddle

.container {
  display: flex;
  flex-direction: column;
}
.a {
  margin: 0 auto;
  border: 1px solid red;
}
.b {
  border: 1px solid blue;
}
<div class="container">
  <div class="a">A</div>
  <div class="b">B</div>
</div>

这就是 flexbox 布局算法的工作原理。在这种情况下,以下内容适用:

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

在您的情况下,您会看到免费的 space 均匀分布在元素的两侧。这是布局算法中的另一点:

9. Flex Layout Algorithm - 9.5. Main-Axis Alignment

Distribute any remaining free space. For each flex line: If the remaining free space is positive and at least one main-axis margin on this line is auto, distribute the free space equally among these margins. Otherwise, set all auto margins to zero. Align the items along the main-axis per justify-content.