Flexbox won't shrink elements after wrapping - why?

Issue

I need to create a flexbox with a maximum width of 500px that wraps beyond that width, but also shrinks to fit the content after the wrapping occurs.

Demonstration

The following codepen demonstrates the issue:
https://codepen.io/heroes-coding/pen/rNaGYmo

HTML / CSS

body {
  background: black;
}

.holder {
  width: 650px;
  background: gray;
  margin-top: 50px;
}

.flexbox {
  display: flex;
  background: blue;
  max-width: 500px;
  width: fit-content;
  flex-wrap: wrap;
}

.item {
  width: 100px;
  height: 50px;
  background: red;
  border-bottom: 1px dotted white;
  border-top: 1px dotted white;
  border-right: 1px dotted white;
}

.item.wide {
  width: 200px;
}
<div class="holder">
  <div class="flexbox">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

Answer

To create a flexbox with a maximum width of 500px that wraps beyond that width, but also shrinks to fit the content after the wrapping occurs, you can use the following CSS code:

.flexbox {
  display: flex;
  background: blue;
  max-width: 500px;
  width: 100%;
  flex-wrap: wrap;
}

.item {
  flex: 1 0 auto;
  width: 100px;
  height: 50px;
  background: red;
  border-bottom: 1px dotted white;
  border-top: 1px dotted white;
  border-right: 1px dotted white;
}

.item.wide {
  width: 200px;
}

Explanation:

  • Set the max-width of the flexbox to 500px.
  • Set the width of the flexbox to 100% to make it shrink to fit the content after wrapping.
  • Use flex: 1 0 auto on the flex items to make them grow and shrink as needed.
  • Remove the background color from the .holder class so that it doesn’t cover the background of the flexbox.