Part 3: We might not need quantity queries thanks to Flexbox

A while ago I wrote a blog post on creating a grid using quantity queries and Flexbox. I used quantity queries to change the widths of items in the grid depending on their position on the grid. Then I used Flexbox to give all the items equal heights. Last week's blog post explored more possibilities with nth-child and Flexbox and I ended up with a similar outcome using less code.

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:

grid-flexbox-grow.png#asset:476Here's the Flexbox magic.

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

.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.

.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.

Flexbox is supported by 97% of browsers.