Feed full of gorgeous images of different sizes, arranging perfectly like bricks in a wall. That’s masonry layout. And it requires JavaScript. Or… does it?

In this article I’m going to show you how you can achieve that look with just CSS.

Preparing the elements

We need bricks to build the wall. Since hardcoding 30 divs isn’t necessarily the most exciting thing to do, we’re just going to use a for loop. Don’t worry though, the styling itself will be done purely with CSS. Let’s use the lorem picsum API to get some nice images from Unsplash as backgrounds for the divs.

for (let i = 0; i <= 30; i++) {
  const div = document.createElement('div');
  div.style.backgroundImage = `url(https://picsum.photos/500/500?random=${i})`;
  document.body.appendChild(div);
}

Set the height and width so we can actually see the images, add some margin, border radius and adjust the background position and size:

div {
  border-radius: 10px;
  background-size: cover;
  background-position: center;
  margin: 0.3em;
  height: 10em;
  width: 10em;
}

Image for post

Photos from Unsplash

Sweet! Now let’s get to the layouts.

#css-grid #web-development #flexbox #css

3 Easy CSS Only Masonry Layouts
3.75 GEEK