1

Why doesn't flex item A take the full width of the container when it's set to 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>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Stickers
  • 75,527
  • 23
  • 147
  • 186

1 Answers1

2

That's how the flexbox layout algorithm works. In this case, the following applies:

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.

In your case, you are seeing the free space distributed equally on both sides of the element. Here is another point taken from the layout algorithm:

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.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304