How to build masonry grid columns

Alexander Khoroshilov
2 min readMar 28, 2023

--

To build a responsive masonry grid with 3 columns for desktop, 2 columns for tablets, and 1 column for mobile devices, you can use CSS Grid or Flexbox combined with media queries. Really simple.

Here’s a simple example HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Masonry Grid Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="masonry-grid">
<div class="masonry-item">
<img src="./images/image1.png" alt="Image 1">
</div>
<div class="masonry-item">
<img src="./images/image2.png" alt="Image 2">
</div>
<div class="masonry-item">
<img src="./images/image3.png" alt="Image 3">
</div>
<div class="masonry-item">
<img src="./images/image4.png" alt="Image 4">
</div>
<div class="masonry-item">
<img src="./images/image5.png" alt="Image 5">
</div>
<div class="masonry-item">
<img src="./images/image6.png" alt="Image 6">
</div>
<div class="masonry-item">
<img src="./images/image7.png" alt="Image 7">
</div>
<div class="masonry-item">
<img src="./images/image8.png" alt="Image 8">
</div>
<div class="masonry-item">
<img src="./images/image9.png" alt="Image 9">
</div>
</div>
</div>
</body>
</html>

Now, let’s write some CSS code, mobile-first of :

body {
margin: 0;
padding: 0;
font-family: sans-serif;
}

.wrapper {
max-width: 980px;
height: auto;
margin: auto;
}

.masonry-grid {
column-gap: 10px;
padding: 10px;
}

.masonry-item {
display: inline-block;
width: 100%;
padding-bottom: 10px;
box-sizing: border-box;
}

.masonry-item img {
width: 100%;
height: auto;
object-fit: cover;
}

/* Mobile-first approach */
/* 1 column for mobile */
.masonry-grid {
column-count: 1;
}

/* 2 columns for tablets */
@media (min-width: 768px) {
.masonry-grid {
column-count: 2;
}
}

/* 3 columns for desktop */
@media (min-width: 1024px) {
.masonry-grid {
column-count: 3;
}
}

Results:

Desktop, Tablet and Mobile views

--

--

Alexander Khoroshilov
Alexander Khoroshilov

Written by Alexander Khoroshilov

Accomplished and innovative Front-end Web Developer with 10 years of experience and extensive experience in web development and full-stack projects.

No responses yet