Skip to content Paweł Grzybek

Native CSS masonry layout

A masonry type of layout, one of the biggest obsessions of UX designers, is finally coming to CSS. Style popularized by Pinterest, where elements fill the vertical gaps instead of being aligned to the row axis.

A default layout alignment vs masonry
A default layout alignment vs masonry

Over the years, we have seen a lot of JavaScript-based solutions to achieve this effect. Masonry by David DeSandro is the most popular one. I created Bricky seven years ago (WOW, time flies 🤯) that solves the same problem. Luckily we can start thinking about getting rid of these hefty libraries.

The grid-template-rows: masonry and grid-template-columns: masonry, defined as part of the CSS Grid Layout Module Level 3, are the modern solution for bricklayer-like designs. At the time of writing this article, the feature is available only in Firefox behind the layout.css.grid-template-masonry-value.enabled flag and Safari Technology Preview.

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  grid-template-rows: masonry;
}

See the Pen 2023.02.09 - CSS Grid: masonry layout test by Pawel Grzybek (@pawelgrzybek) on CodePen.

Keep in mind accessibility — the default (pack) item placement algorithm may cause an unintended tabbing order. Luckily, a masonry-auto-flow gives us granular control over the item’s placement.

I miss writing about CSS. This language gets more and more incredible features at an unstoppable rate, so expect more posts about it.

Comments

  • R
    Rich Wertz

    With very few and limited exceptions, this isn't supported in any widely used browser. At least with FireFox, you can enable it. https://caniuse.com/?search=grid-template-rows%3A%20masonry

    👆 you can use Markdown here

    Your comment is awaiting moderation. Thanks!
    • Pawel Grzybek
      Pawel Grzybek

      Thats fine :) Nothing stops me from experimenting with things that will be widely adopted soon. I am sure you can't live with CSS Grid now, but do you remember how crazy an idea it was three years ago? Exactly!

      👆 you can use Markdown here

      Your comment is awaiting moderation. Thanks!

Leave a comment

👆 you can use Markdown here

Your comment is awaiting moderation. Thanks!