3

I can't work out why the last item stretches to fill the width of the container, how can I change things so that it only fills 50% like the others?

.container {
    margin-top: 30px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.item {
    flex: 50%;
    background:green;
}
<div class="container">
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
  <div class="item">
    Item
  </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
fightstarr20
  • 11,682
  • 40
  • 154
  • 278

1 Answers1

6

You are sizing your flex items using the flex shorthand property.

This property takes three values:

  • flex-grow
  • flex-shrink
  • flex-basis

The key point to understand is that omitting values in the flex property doesn't actually remove those values, it activates fallback values.

You have flex: 50%.

That rule omits flex-grow and flex-shrink.

As defined in the flexbox specification, when omitted in the flex property, flex-grow defaults to 1 and flex-shrink defaults to 1.

So flex: 50% is equivalent to flex: 1 1 50%. That's why your last item consumes all free space.

Here are two solutions to the problem:

  1. Replace flex: 50% with flex-basis: 50%. This leaves the flex-grow property at its standard default setting, which is 0.

OR

  1. Replace flex: 50% with flex: 0 0 50%, which overrides any default flex property settings.

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 0 0 50%;
  background: lightgreen;
}
<div class="container">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701