Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a masonry layout

Short answer

The simplest way today is multi-column layout: the cards flow top to bottom and fill the columns without holes:

<style>
  .wall { columns: 3 100px; column-gap: 8px; }
  .wall div { break-inside: avoid; margin-bottom: 8px; padding: 8px; background: lavender; border-radius: 8px; }
</style>
 
<div class="wall">
  <div style="height: 60px">1</div><div style="height: 100px">2</div><div style="height: 40px">3</div>
  <div style="height: 80px">4</div><div style="height: 50px">5</div><div style="height: 90px">6</div>
</div>

columns: 3 100px means "at most three columns at least 100px wide", and break-inside: avoid keeps a card from being split between columns.

The catch

The order runs by column: the first one fills up, then the second. That does not matter for a gallery, but it does not suit a news feed where the order is read left to right.

The future: grid masonry

The spec has a true grid masonry layout with row order, but not every browser supports it yet. Until then, use the columns above or a small script.

Common mistake

Without break-inside: avoid a card can start at the bottom of one column and continue at the top of the next. And margin-bottom is used instead of gap because columns have no vertical gap between items.

Functions used in this recipe

  • display — Decides how an element behaves in the flow and how it lays out its content.
  • gap — The gaps between items in flexbox and grid.
  • height — The height of an element.

Thanks for reading!

Donate to the site — we work hard for you.