skip to main content

CSS masonry with flexbox, :nth-child(), and order
tobiasahlin.com

Tobias Ahlin:

On the surface it seems fairly easy to create a masonry layout with flexbox; all you need to do is set flex-flow to column wrap` and voilà, you have a masonry layout. Sort of. The problem with this approach is that it produces a grid with a seemingly shuffled and obscure order. Items will be (unbeknownst to the user) rendered from top to bottom and someone parsing the grid from left to right will read the boxes in a somewhat arbitrary order, for example 1, 3, 6, 2, 4, 7, 8, 5, and so on so forth.

Flexbox has no easy way of rendering items with a column layout while using a row order, but we can build a masonry layout with CSS only—no JavaScript needed—by using :nth-child() and the order property.

This is very clever — an actually helpful use of order that helps visual order more accurately follow source order.

But there’s a catch: it requires a fixed height for the container — and it needs to be a magic number that’s taller than the tallest column. That unfortunately makes it not super resilient to content changes, limiting its usefulness.