CSS Grid Layout Module Level 2: Masonry Layout

UPDATE 2020.10.22: Masonry Layout founds its home in the CSS Grid Module Level 3 Draft Spec!

A long requested CSS feature is to be able to create a “Masonry Layout” using pure CSS. Today we can already create a Masonry-like layout using grid-auto-flow: dense;, but unfortunately that’s not the real deal.

🤔 Masonry Layout?

Masonry is a grid layout based on columns, as popularized by Pinterest. Unlike other grid layouts, it doesn’t have fixed height rows. It works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall.

It became easy to implement thanks to the Masonry JavaScript Library.

~

Thankfully discussions to natively implement Masonry in CSS haven’t stopped and back in January it kinda settled on this syntax:

.masonry {
  display: grid;
  grid-gap: 1em;
  grid: masonry / repeat(auto-fit, minmax(20em, 1fr));
}

☝️ That’s grid-template-rows being set to masonry there, and grid-template-columns to the already familiar repeat(auto-fit, minmax(20em, 1fr))

Knowing that Tab Atkins – author of CSS Grid Layout Level 1 – responded with I’m liking this quite a bit! was a good sign. What’s even better is that Firefox Nightly (version 77a1) has implemented it by now, behind a flag.

👨‍🔬 Do note that this Masonry addition is still a proposal and is considered to be highly experimental at the time of writing. The syntax is still being discussed upon and is NOT final at all. Heck, you can’t even find a mention of Masonry in the CSS Grid Module Level 2 Draft!

~

To enable the experimental Masonry implementation in Firefox Nightly go to about:config and set layout.css.grid-template-masonry-value.enabled to true.

Once enabled the following pen should show a nice Masonry Layout:

See the Pen CSS Masonry Layout (FF Nightly – Feature Flag) by Miriam Suzanne (@mirisuzanne) on CodePen.

Yes, I’m really excited about this one … let’s hope it sticks!

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

BuymeaCoffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

3 Comments

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.