Building Masonry-Like Layouts with Grid

What a Masonry Layout Is

A masonry layout arranges items of varying heights into columns with minimal gaps, similar to how bricks are laid - unlike a strict grid, where every row's height is set by its tallest item, leaving awkward gaps under shorter neighbors.

Why Regular Grid Struggles With This

A standard CSS Grid places items into strict rows, so if one card in a row is much taller than its neighbors, every item in that row is forced to align to the same row boundaries, leaving empty space beneath the shorter cards.

An Approximation with grid-auto-flow: dense

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-auto-flow: dense;
  grid-auto-rows: 10px; /* a small, fine-grained row unit */
}
.item {
  grid-row: span var(--span, 20); /* set per item based on its content height */
}

By using a very small grid-auto-rows value and having each item span a number of these tiny rows proportional to its own height, items can pack more tightly and fill gaps - though this requires calculating a span value per item, often with a small script that measures actual rendered height.

A Simpler Alternative: Multi-Column Layout

.gallery {
  columns: 4;
  column-gap: 16px;
}
.item {
  break-inside: avoid;
  margin-bottom: 16px;
}

CSS multi-column layout naturally produces a masonry-like effect by flowing items down each column in turn, though items are ordered top-to-bottom within a column rather than left-to-right across the whole gallery, which can affect reading order.

A Native masonry Value Is Coming

A dedicated grid-template-rows: masonry value is being standardized for CSS Grid itself, which would remove the need for these workarounds - worth checking current browser support before relying on it in production.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.