CSS

Auto-Spacing Last Row Flex Items in Wrapped Layouts

Master a technique to correctly distribute space or align the last item(s) in a wrapped flexbox container, useful when `justify-content: space-between` isn't sufficient.

.flex-gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* or space-between */
  gap: 20px;
  padding: 20px;
  max-width: 800px; /* Constrain for wrapping */
  border: 2px dashed #999;
}

.gallery-item {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  padding: 20px;
  width: 180px; /* Fixed width for demonstration */
  flex-shrink: 0; /* Prevent shrinking */
  text-align: center;
  line-height: 20px;
}

/* Target the last item on the last row to push it to the right */
.gallery-item:last-child {
  margin-left: auto; /* Pushes the last item to the far right if it's the only one on its row */
}

/* Alternative: If you want to simulate space-between on the last row */
/*
.flex-gallery::after {
    content: "";
    flex: auto;
    min-width: 180px; /* Match item width */
}
*/
How it works: When `justify-content: space-between` is used on a `flex-wrap: wrap` container, the last row's items might not distribute space as expected if there aren't enough items to fill the row completely. This snippet provides a common workaround: applying `margin-left: auto` to the last child. If the last item is the sole item on its line, `margin-left: auto` pushes it to the far right. For more complex `space-between` simulation on the last line, a pseudo-element (`::after`) can be used as a 'dummy' flex item to consume remaining space.

Need help integrating this into your project?

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

Hire DigitalCodeLabs