Expand last row of wrapped flex items to fill entire row

Thanks to Jonathan Snook, I’ve learnt that we don’t need quantity queries to create a balanced grid. Quantity queries are very powerful, but so is Flexbox. If we just want all the items in the last row to fill the space, regardless of how many there are, then Flexbox can take care of this. But if we want to add additional styles to the items, we still need quantity queries.

This is the grid we want to achieve:

Here’s the Flexbox magic.

The container needs to have the property display: flex; and the items need to be wrapped using flex-wrap: wrap;

Code language: CSS

.list {
    display: flex;
    flex-wrap: wrap;
}

Now here’s the clever bit. We can set an initial width to the items (in this case flex-basis: 23%;) so that each item will always get a width of 23% unless otherwise stated in the CSS. flex-grow: 1; tells the items to grow and fill the space in the row.

Code language: CSS

.list-item {
    ...
    flex-basis: 23%;
    flex-grow: 1;
}

So, thanks to flex-grow, no matter how many items are in the last row, they will always fill the space. Works like magic! It’s amazing how much can be achieved with so little CSS.