user1198411
user1198411

Reputation: 149

How can I make flex items shrink until wrapping is necessary, and then expand to fill the new space?

I have a flexbox parent component with width about 1200px, and several child items with min-width about 400px. Nominally, with a screen width above 1200, and taking into consideration margins and borders, I can fit two child items per row, each about 600px wide.

With a decreasing screen width from about 1200px to about 800px, the two child items gradually shrink down to about 400px. When the screen size goes below about 800px, wrapping occurs, meaning I now have one child item per row.

What I would like is for those child items to expand back to about 800px to fill their rows. What I get is child items that remain at about 400px wide.

If I set grow: 1 on the child items, they start off at one per row, each using the full 1200px.

I'm hoping that there is some combination of min-width, flex-basis, max-width, and grow (and maybe something else) that can achieve my desired result.

I would appreciate any suggestions.

Upvotes: 0

Views: 2488

Answers (1)

Mattias Martens
Mattias Martens

Reputation: 1647

Here's a snippet that I believe achieves what you want:

<div>
  <div class="container">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
  </div>
</div>
<style>
  .container {
    display: flex;
    max-width: 1200px;
    flex-wrap: wrap;
  }

  .box {
    outline: solid red 1px;
    min-width: 400px;
    flex-grow: 2;
    /* flex: 2 0 50%; */ /* If you want to ensure that you never get more than 2 items per row */
  }
</style>

In sum, the property you want is flex-grow: it ensures that the component will fill up available space on its row up to the specified factor (in this case 2, to go from 400px width up to 800px).

If it's important not to fit more than two elements on a row on wider screens, I added an alternative flex property for that which uses a flex-basis of 50% to make the components "greedier" in flowing onto a row than they would be otherwise.

Upvotes: 1

Related Questions