Search code examples
cssflexbox

How to make flexbox items the same width when they have only min and max width defined?


I'm trying to make all items the same width in flexbox container when they have only max-width and min-width defined. It's flex row with wrapped lines. With setting flex grow to 1 and flex basis to 0 I'm able to achive the same width for all items expect last line if there is extra space left.

I'm wonder if it's even possible to have all flex items the same width without specified width.

Here is example:

.container {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 200px;
  gap: 10px;
  background-color: lightseagreen;
}

.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  background-color: coral;
  padding: 10px;
  min-width: 100px;
  max-width: 150px;
  height: 40px;
}
<div class="container">
  <div class="item">some text</div>
  <div class="item">some other text but longer</div>
  <div class="item">longer</div>
  <div class="item">some other</div>
  <div class="item">some other text but longer</div>
</div>

I would like to make the last div the same width as others but at the same time I would like to make divs in first and second row fill the space.


Solution

  • I accomplished my goal with grid and without fixed width. Grid's grid-template-columns let me do exactly what I wanted. The only caveat of this solution is that the grid ignores the max-width of its items. It will work only if handling max-width can be moved from children to parent.

    I'm posting an example with a code that responds to my question but in a specific place in a project that I wanted to implement it works much better without max-width and with minmax(100px, 1fr).

    .container {
      display: grid;
      grid-auto-rows: auto;
      grid-template-columns: repeat(auto-fit, minmax(100px, 145px));
      gap: 10px;
      width: 300px;
      background-color: lightseagreen;
    }
    
    .item {
      background-color: coral;
      padding: 10px;
      min-width: 100px;
      max-width: 150px;
      height: 40px;
    }
    <div class="container">
      <div class="item">some text</div>
      <div class="item">some other text but longer</div>
      <div class="item">longer</div>
      <div class="item">some other</div>
      <div class="item">some other text but longer</div>
    </div>