Flex items create space between them when they wrap [duplicate]

When you create a flex container, an initial setting is align-content: stretch.

This causes multiple lines of flex items to distribute themselves evenly along the cross axis of the container. It’s kind of like setting flex: 1 along the main axis: the flex items spread evenly across the line.

As a result, align-content: stretch may cause gaps when flex items wrap.

The simple solution is to override this setting with align-content: flex-start.

revised fiddle

html,
body {
  width: 100%;
  height: 100%;
}
#container {
  display: flex;
  height: 100%;
  background-color: blue;
}
.block {
  flex: 1;
}
#left {
  background-color: green;
}
#center {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  align-content: flex-start; /* NEW */
}
#right {
  background-color: orange;
}
.flexContainer {
  flex: 1;
  width: 50%;
  min-width: 100px;
  max-width: 50%;
  height: 150px;
  background-color: red;
  padding: 10px;
}
.flexDiv {
  width: 100%;
  height: 100%;
  background-color: yellow;
}
<div id="container">
  <div id="left" class="block">Left</div>
  <div id="center" class="block">
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
  </div>
  <div id="right" class="block">Right</div>
</div>

Reference:

8.4. Packing Flex Lines: the align-content
property

The align-content property aligns a flex container’s lines within
the flex container when there is extra space in the cross-axis,
similar to how justify-content aligns individual items within the
main-axis. Note, this property has no effect on a single-line flex
container.

The property accepts six values. stretch is the default.

stretch

Lines stretch to take up the remaining space. If the leftover free-space is negative, this value is identical to flex-start. Otherwise, the free-space is split equally between all of the lines, increasing their cross size.

The remaining values are: flex-start / flex-end / center / space-between / space-around

Leave a Comment