CSS

Aligning Last Row Items in a Flexbox Wrap

Learn to perfectly align the last row of items in a wrapping Flexbox container, ensuring even distribution and preventing awkward gaps for a clean grid-like appearance.

.flex-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between; /* Distribute items with space between */
    gap: 20px; /* Space between items */
    padding: 20px; /* Container padding */
    background-color: #f9f9f9;
}

.flex-grid__item {
    flex-basis: calc(33.33% - (20px * 2 / 3)); /* For 3 columns, adjust for gap */
    max-width: calc(33.33% - (20px * 2 / 3)); /* Ensures max width for 3 items */
    background-color: #c9e9fe;
    padding: 20px;
    border-radius: 8px;
    box-sizing: border-box;
    text-align: center;
    font-family: sans-serif;
}

/* The trick: Add placeholder elements to absorb space on the last row.
   For N columns, you typically need N-1 placeholders. This example is for 3 columns. */
.flex-grid::before,
.flex-grid::after {
    content: "";
    flex-basis: calc(33.33% - (20px * 2 / 3)); /* Match item width */
    /* These pseudo-elements are invisible but take up space */
}
How it works: This snippet addresses a common Flexbox challenge: aligning items in the last row of a wrapped container when there aren't enough items to fill it completely. By setting `justify-content: space-between` on the container and adding pseudo-elements (`::before` and `::after`) that match the `flex-basis` of the actual items, these pseudo-elements act as invisible placeholders. They absorb the extra space, forcing the actual items in the last row to align perfectly with the items in the preceding rows, creating a clean, grid-like appearance without extra markup. The `gap` property provides consistent spacing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs