eclipse eclipse - 6 months ago 8
HTML Question

Flex-box: flex-shrink and flex-wrap not working as expected

My problem can best be explained with this example: [JSFiddle]

#flex-container-1 { /*has 10 items*/
flex-wrap: no-wrap;
}

#flex-container-2 { /*has 10 items*/
flex-wrap: wrap;
}

#flex-container-3 { /*has 11 items*/
flex-wrap: wrap;
}


I have three containers of which two function as expected.
But the third is not shrinking the 11th element but instead appending it outside the container.

Is there a way to shrink the items in the third container so it does not overflow?

[JSFiddle] https://jsfiddle.net/fpcz3ghc/1/.

The height of the container should be fixed.

Answer

Don't define the fixed height on .flex-item. Instead set a max-height:50px;.

Try the following solution:

.flex-container {
  height: 100px;
  width: 200px;
  background-color: black;
  display: flex;
  margin: 50px;
}
#flex-container-1 {
  flex-wrap: no-wrap;
}
#flex-container-2 {
  flex-wrap: wrap;
}
#flex-container-3 {
  flex-wrap: wrap;
}
.flex-item  {
  max-height:50px;
  flex-basis: 50px;
  background-color:red;
  border-radius: 20px;
}
<div id="main">
  <div id="flex-container-1" class="flex-container">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
  </div>
  <div id="flex-container-2" class="flex-container">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
  </div>
  <div id="flex-container-3" class="flex-container">
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
    <div class="flex-item"></div>
  </div>
</div>

Comments