CSS

Flexbox: Distributing Last Row Items with Space-Between

Create responsive Flexbox layouts where items wrap to new lines, ensuring the items on the last row are evenly distributed across the container width using a simple technique.

.flex-container-wrap {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* Distributes space on each line */
  gap: 1rem; /* Space between items and lines */
  padding: 1rem;
  background-color: #f0f0f0;
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  box-sizing: border-box; /* Include padding in width */
}

.flex-item-wrap {
  flex: 1 1 200px; /* grow, shrink, basis (min width 200px) */
  height: 120px;
  background-color: #6a5acd;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
  font-size: 1.2rem;
  min-width: 200px; /* Ensure a minimum width */
  max-width: calc(33.33% - 1rem); /* Example: 3 items per row with gap */
}

/* The "ghost" items to force space-between behavior on the last row */
/* Add as many of these as 'max items per row minus 1'. */
/* For 3 items per row, we need 2 ghosts. */
.flex-container-wrap::after,
.flex-container-wrap::before {
  content: "";
  flex: 1 1 200px; /* Match item's flex-basis */
  max-width: calc(33.33% - 1rem); /* Match item's max-width */
  height: 0;
  visibility: hidden;
}


<div class="flex-container-wrap">
  <div class="flex-item-wrap">Item 1</div>
  <div class="flex-item-wrap">Item 2</div>
  <div class="flex-item-wrap">Item 3</div>
  <div class="flex-item-wrap">Item 4</div>
  <div class="flex-item-wrap">Item 5</div>
  <!-- If max 3 items per row, this will force 4&5 to space-between -->
</div>
How it works: This snippet solves the common Flexbox challenge of making the last row of wrapped items justify with `space-between` when there aren't enough items to fill the row completely. By default, `justify-content: space-between` only applies to the items present on that specific line. To force the last row to spread out, "ghost" pseudo-elements (`::before` and `::after`) are added to the container. These invisible elements match the `flex-basis` and `max-width` of the actual items, effectively filling the "missing" item slots and tricking Flexbox into distributing the visible items evenly across the full width of the last row.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs