Google Login with Google

Masonry Gallery in HTML, CSS & JavaScript

📌 What is a Masonry Layout?

A masonry layout arranges items like bricks.

👉 Instead of fixed rows,
items are placed based on height.

Used in:

Pinterest
portfolio sites
image galleries
1️⃣ Basic HTML structure
<div class="gallery">
<div class="item"><img src="img1.jpg"></div>
<div class="item"><img src="img2.jpg"></div>
<div class="item"><img src="img3.jpg"></div>
<div class="item"><img src="img4.jpg"></div>
</div>
2️⃣ Masonry using CSS (column method)
.gallery {
column-count: 4;
column-gap: 10px;
}

.item {
break-inside: avoid;
margin-bottom: 10px;
}

.item img {
width: 100%;
display: block;
border-radius: 10px;
}

👉 This is the simplest way

3️⃣ Responsive design
@media (max-width: 1024px) {
.gallery {
column-count: 3;
}
}

@media (max-width: 768px) {
.gallery {
column-count: 2;
}
}

@media (max-width: 480px) {
.gallery {
column-count: 1;
}
}

👉 Adjust columns by screen size

4️⃣ Alternative: JavaScript Masonry

If you want more control:

Use Masonry library:

<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script>
var grid = document.querySelector('.gallery');
new Masonry(grid, {
itemSelector: '.item',
columnWidth: '.item',
percentPosition: true
});
</script>
🔥 Key Features
responsive layout
dynamic height support
clean visual grid
⚠️ CSS vs JS method
Method Pros Cons
CSS columns simple order issues
JS Masonry precise layout extra library
🔐 Performance Tip
optimize images
use lazy loading
<img src="img.jpg" loading="lazy">
✅ Summary

To build masonry gallery:

create HTML structure
use CSS columns
make responsive
(optional) use JS library
🚀 Next Step

You can extend this by:

image modal (click to enlarge)
infinite scroll
filtering (category tags)

Hope this helps 🚀
← Back to list
💬 Comments (0)