DEV Community

Cover image for A Responsive Image Gallery in ~30 Lines (Grid + Lightbox, No Library)
DesignToCodes
DesignToCodes

Posted on • Originally published at designtocodes.com

A Responsive Image Gallery in ~30 Lines (Grid + Lightbox, No Library)

You don't need a carousel library for a gallery. CSS grid + ~15 lines of JS gives you a responsive, lazy-loaded gallery with a lightbox — and it loads faster than any plugin. Copy-paste below.

Grid does the responsive part for free

.gallery{display:grid;gap:12px;
  grid-template-columns:repeat(auto-fill,minmax(240px,1fr))}
.gallery img{width:100%;height:100%;object-fit:cover;border-radius:8px}
Enter fullscreen mode Exit fullscreen mode

auto-fill + minmax() = reflows on every screen, zero media queries.

Lightbox, no library

const g=document.querySelector('.gallery');
const box=Object.assign(document.createElement('div'),{className:'lightbox'});
document.body.append(box);
g.addEventListener('click',e=>{const a=e.target.closest('a');if(!a)return;
  e.preventDefault();box.innerHTML='<img src="'+a.href+'">';box.classList.add('open');});
box.addEventListener('click',()=>box.classList.remove('open'));
Enter fullscreen mode Exit fullscreen mode

The perf bits that matter

  • WebP/AVIF thumbnails sized to their slot (not 3000px into 400px)
  • loading="lazy" below the fold
  • width/height set → no layout shift
  • Full-res image loads only in the lightbox, on click

Want a tested one? Grab a free responsive gallery section.

Vanilla lightbox or a library — what do you reach for? 👇

Top comments (0)