Flex container stretches to full width when items wrap

45 views Asked by At

I want the flex container to expand as much as the largest row when the items wrap. Given the container below, it should expand as much as the first row, leaving no gap on the sides.

enter image description here

#main {
  display: inline-flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
  border: 1px solid #c3c3c3;
}

#main div {
  height: 50px;
}
<div style="width: 200px; text-align: center;">
  <div id="main">
    <div style="width: 145px; background-color:coral;">1</div>
    <div style="width: 40px; background-color:lightblue;">2</div>
    <div style="width: 70px; background-color:khaki;">3</div>
    <div style="width: 100px; background-color:pink;">4</div>
  </div>
</div>

1

There are 1 answers

1
DustInComp On

Add width: min-content to the flex div.

#main {
  width: min-content;
  display: inline-flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
  border: 1px solid #c3c3c3;
  text-align: center;
}
<div style="width:200px;">
  <div id="main">
    <div style="width:145px;height:50px;background-color:coral;">1</div>
    <div style="width:40px;height:50px;background-color:lightblue;">2</div>
    <div style="width:70px;height:50px;background-color:khaki;">3</div>
    <div style="width:100px;height:50px;background-color:pink;">4</div>
  </div>
</div>