Finally a CSS-only solution to create masonry layouts

Temani Afif - Mar 4 '21 - - Dev Community

hold on! the below feature is experimental and can be tested only on Firefox

The specification of CSS Grid Level 3 is actually under construction and it's about masonry layout

This module introduces masonry layout as an additional layout mode for CSS Grid containers.

What the hell is masonry?

It's what you see when navigating Pinterest. Something like the below:

Masonry layout
figure taken from the linked specification

We used to build this using JS or a lot of hacky CSS but now only one CSS property can do it.

.container {
  grid-template-rows: masonry; 
}
Enter fullscreen mode Exit fullscreen mode

Yes, only this!

Here is what a full code will look like:

<div class="container">
  <img src="https://picsum.photos/id/1/200/300">
  <img src="https://picsum.photos/id/17/200/400">
  <img src="https://picsum.photos/id/18/200/100">
  <img src="https://picsum.photos/id/109/200/200">
  <img src="https://picsum.photos/id/1069/200/600">
  <img src="https://picsum.photos/id/120/200/150">
  <img src="https://picsum.photos/id/130/200/100">
  <img src="https://picsum.photos/id/203/200/100">
  <img src="https://picsum.photos/id/109/200/200">
  <img src="https://picsum.photos/id/11/200/100">
  <img src="https://picsum.photos/id/119/200/100">
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: grid;
  grid-template-columns: repeat(auto-fil, minmax(200px, 1fr));
  grid-template-rows: masonry; /* this will do the magic */
  grid-gap: 10px;
}
img {
  width:100%;
}
Enter fullscreen mode Exit fullscreen mode

You can test the above on Firefox but you need to first enable a flag:

  1. open Firefox and write about:config in the url bar
  2. do a search using masonry
  3. you will get one flag, make it true

Flag

You should get the following result:

Masonry layout

Which is fully responsive thanks to repeat(auto-fil, minmax(200px, 1fr))

CSS masonry

We can also have the other direction by adjusting the CSS like below:

.container {
  display: grid;
  grid-template-rows: repeat(auto-fil, minmax(200px, 1fr));
  grid-template-columns: masonry; 
  grid-gap: 10px;
  height:100vh;
}
img {
  height:100%;
}
Enter fullscreen mode Exit fullscreen mode

Masonry horizontal

The specification introduces many other properties to control our masonry grid but it's still early to investigate them since they may change at any time.

Worth to note that the CSS Grid Level 2 is still not fully implemented by all the browsers so we need to be patient for the Level 3.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .