CSS

Prevent Orphaned Last Flex Item in `space-between` Layout

Prevent the last flex item from being left alone at the start of a row when using `justify-content: space-between` and `flex-wrap`, ensuring consistent distribution.

<div class="flex-container">
  <div class="flex-item">Item 1</div>
  <div class="flex-item">Item 2</div>
  <div class="flex-item">Item 3</div>
  <div class="flex-item">Item 4</div>
  <div class="flex-item">Item 5</div>
  <!-- Add "filler" divs to mimic full rows for space-between. For N items per row, add N-1 fillers. -->
  <div class="flex-item--filler"></div>
  <div class="flex-item--filler"></div>
</div>

<style>
.flex-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* This is the key property */
  gap: 20px; /* Gap between rows and columns */
  max-width: 900px;
  margin: 20px auto;
  border: 1px solid #ddd;
  padding: 10px;
}

.flex-item,
.flex-item--filler { /* Both actual items and fillers share sizing */
  /* Example: Aim for 3 items per row with 20px gap */
  /* Calculation: calc((100% - ((N-1) * gap)) / N) where N is target items per row */
  flex: 0 0 calc((100% - (2 * 20px)) / 3); 
  min-width: 200px; /* Ensure items don't shrink too much */
  height: 100px; /* Example fixed height for visual */
  background-color: #a7d9f7;
  padding: 20px;
  text-align: center;
  box-sizing: border-box;
}

/* Hide the filler items visually */
.flex-item--filler {
  background-color: transparent;
  border: none;
  visibility: hidden; /* Make them invisible, but occupy space */
}
</style>
How it works: The `justify-content: space-between` property distributes available space only *between* flex items. When `flex-wrap` causes items to flow to a new line, and the last row has fewer items than previous rows, those items are pushed to the start, creating an 'orphan' effect. To prevent this, we add invisible 'filler' elements (`.flex-item--filler`) to the HTML. These fillers share the same `flex-basis` as the actual items, effectively tricking `space-between` into distributing space as if the row were full. By making them invisible, they occupy space without being seen, ensuring consistent alignment for all items. The number of filler items should be `N-1` where `N` is the desired number of items per full row (e.g., 2 fillers for 3 items per row).

Need help integrating this into your project?

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

Hire DigitalCodeLabs