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

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.

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.

Beware though: this technique requires you to set a fixed height on the wrapper, which is not always possible 😕

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

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.