Subscribe

Native CSS Masonry layouts

✍️

Finally a specification for CSS native masonry grid.

27 Mar, 2021 · 2 min read

I’m excited about this feature, although it’s not yet widely supported.

Making masonry grids is so cool! It’s that elemental table effect, where blocks of different sizes can stack. (Like Tetris!)

And yes, we could do this before, with some JavaScript or come very close with flex and grid, but it wasn’t perfect.

Now there is the masonry option for grid-template-rows.

Note: This is unfortunately far from being well supported, so do note that!

The result can look like this:

CSS Masonry layout

Enabling masonry support

We can currently try out the feature in Firefox, but we need to enable it first.

Open Firefox and type the following in the address bar: about:config.

Then type: layout.css.grid-template-masonry-value.enabled and set this to true.

Now we can enjoy CSS native grids!

Creating our masonry grid

To create the grid, we use CSS grid options.

Let’s start by creating a basic structure:

<div class="container">
  <img src="1.jpg" />
  <img src="2.jpg" />
  <img src="3.jpg" />
  ...
</div>

Here you can add some images of all kinds of shapes that will become masonry’s magic to fix.

Now let’s add the magic in CSS.

.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: masonry;
  gap: 10px;
}

And yes, that’s it! All we need to create masonry layouts.

In a browser that doesn’t support it, we get the following result:

Browser that doesn't support CSS masonry

However, in browsers that do support it, we see the following:

CSS Masonry layout

Wow, right? It just auto-filled where each image should go, and it looks fantastic.

I’m super amped for this feature to become widely supported.

For those that use Firefox, enable the flag and check it out on this Codepen.

See the Pen Native CSS Masonry layouts by Chris Bongers (@rebelchris) on CodePen.

Browser support

Unfortunately, it’s really new and therefore not supported. We have to enable a flag in Firefox to see it in action.

To enable Firefox, set the following flag to true. layout.css.grid-template-masonry-value.enabled.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Modifying an SVG path with CSS

10 Dec, 2022 · 2 min read

Modifying an SVG path with CSS

Animate an SVG path with CSS

9 Dec, 2022 · 2 min read

Animate an SVG path with CSS

Join 2099 devs and subscribe to my newsletter