Build a CSS Grid Image Gallery With Masonry and a Lightbox

a CSS grid image gallery needs one container with display: grid and grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)), plus aspect-ratio and object-fit: cover on the images. That gives you a responsive gallery with no media queries. Add about 30 lines of JavaScript around the native <dialog> element and you have a lightbox. Swap the fixed ratio for small grid-auto-rows and you get a masonry layout.

This tutorial builds the whole thing step by step, with snippets you can paste into any project. You won’t need a gallery plugin or a framework. Each step explains why the code works, so you can adapt it when a client asks for “the same thing, but with a big featured photo first”.

How a CSS grid image gallery works

CSS Grid Layout is a two-dimensional layout system. You declare columns on a parent element, and the browser places every child into the next free cell. The browser creates rows automatically as images flow in, which is exactly what a gallery needs: you control the columns, and the number of rows follows the number of photos.

Three ideas carry the whole gallery. Tracks are the columns and rows, sized with units like fr (a fraction of the free space). The gap property spaces the tracks, so you never fight margins on the first or last item of a row. And items can span several tracks, which is how you get featured tiles and masonry.

Should you use Flexbox instead? Flexbox works in one dimension, a row or a column at a time.

A gallery with aligned rows and columns is a grid problem, so use Grid. Flexbox still shines for justified rows where each photo keeps its own width. CSS Grid has worked in Chrome, Firefox, Safari and Edge since 2017, so browser support is no longer a reason to avoid it. The piece Responsive Photo Gallery with CSS GRID makes a good next read.

Your gallery Use Avoid
Portfolio or product grid, same-size tiles Grid + auto-fit + aspect-ratio Floats or inline-block hacks
Mixed portrait and landscape photos, original shapes kept Masonry with grid-auto-rows, or CSS columns Forcing square crops on artwork
Editorial page with one hero photo Grid + span or grid-template-areas grid-auto-flow: dense if reading order matters
Photos in rows of equal height, varied widths Flexbox with flex-wrap Grid with fixed columns
Hundreds of photos with filters and sorting A dedicated library, or a feature of your CMS (content management system) Hand-rolling everything
photo gallery grid

Step 1: write HTML that works before the CSS loads

Start with markup that makes sense on its own. Each photo sits in a <figure>, with an optional <figcaption>. Wrap the thumbnail in a link to the full-size file. If the JavaScript never runs, the link still opens the large image, which is progressive enhancement at no cost.

<ul class="gallery">
  <li>
    <figure>
      <a href="img/harbour-large.jpg">
        <img src="img/harbour-600.jpg" width="600" height="400"
             alt="Fishing boats moored in a harbour at dawn" loading="lazy">
      </a>
      <figcaption>Harbour at dawn</figcaption>
    </figure>
  </li>
  <!-- more items -->
</ul>

A list tells screen readers how many photos the gallery holds. The width and height attributes give the browser the image’s proportions before the file arrives, so it can reserve the space. The alt text describes what the photo shows, not its file name. The Web Content Accessibility Guidelines (WCAG) 2.1, success criterion 1.1.1 (Non-text Content) requires a text alternative for every meaningful image.

Step 2: responsive columns with auto-fit and minmax()

Here is the core of the layout. One declaration replaces a stack of media queries:

.gallery {
  list-style: none;
  margin: 0;
  padding: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
  gap: 1rem;
}
.gallery figure { margin: 0; }
.gallery img {
  display: block;
  width: 100%;
  height: auto;
}

Read the column rule from the inside out. minmax(14rem, 1fr) sets each column to at least 14rem and at most one share of the free space.

repeat(auto-fit, …) then asks the browser to fit as many of those columns as the container allows. The min(100%, 14rem) wrapper is the safety net: on a phone narrower than 14rem plus padding, the column shrinks to the container width instead of overflowing sideways.

auto-fit and auto-fill look identical until a row isn’t full. Picture three photos in a wide container. auto-fit collapses the empty tracks and stretches the three tiles to fill the row. auto-fill keeps the empty tracks, so the tiles stay at their minimum width. For a gallery whose length changes, auto-fill usually looks more consistent; for a short showcase, auto-fit fills the space better.

Prefer explicit breakpoints? A mobile-first version is just as valid, and some teams find it easier to read:

.gallery { display: grid; gap: 1rem; grid-template-columns: 1fr; }
@media (min-width: 40em) { .gallery { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 64em) { .gallery { grid-template-columns: repeat(4, 1fr); } }

Use this when the design calls for an exact column count at each width, for example a client mockup with four columns on desktop and two on tablet.

step 3 uniform thumbnails with aspect-ratio and object-fit

Step 3: uniform thumbnails with aspect-ratio and object-fit

Real photo sets mix portrait and landscape shots, and the grid looks ragged. Two properties fix it:

.gallery img {
  aspect-ratio: 4 / 3;
  object-fit: cover;
  object-position: center;
}

aspect-ratio gives every thumbnail the same shape. object-fit: cover fills that box while keeping the photo’s proportions, and crops whatever overflows. A practical starting point: 1 / 1 for product and portfolio grids, 4 / 3 for mostly landscape photography, 16 / 9 for video stills.

To change the look from one page to another, store the values in CSS custom properties (variables) such as --gallery-min: 14rem and --gallery-gap: 1rem, then reuse them with var(). A client theme can then switch the gallery density without touching the layout rules.

Cropping has a cost. A portrait headshot cropped to 4 / 3 can lose the top of the head, so shift the focus with object-position: top on those items. For artwork, posters or anything where the frame matters, skip the crop and use the masonry variation below.

Featured images with spans and grid areas

Magazines and agency portfolios often lead with one large image. Make an item span two columns and two rows:

.gallery .featured {
  grid-column: span 2;
  grid-row: span 2;
}
.gallery .featured img { height: 100%; aspect-ratio: auto; }

Note that span 1 is the default, so there’s no need to write it on regular items. On a single-column phone layout, a span 2 item forces an extra column and breaks the grid. Wrap the rule in a media query that only applies once there’s room for two columns.

Spans can leave holes when a big item doesn’t fit at the end of a row. grid-auto-flow: dense back-fills those holes with later items. It looks tidy, but the visual order no longer matches the HTML order. Keyboard users then tab through the photos in a different sequence than they see them, which works against WCAG 2.4.3 (Focus Order). Use dense for decorative grids only.

For a fixed composition, such as three photos on a landing page, grid-template-areas is the most readable option because the CSS draws the layout:

.trio {
  display: grid;
  grid-template-columns: 2fr 1fr;
  grid-template-rows: repeat(2, 1fr);
  grid-template-areas: "main top" "main bottom";
  gap: 1rem;
}
.trio :nth-child(1) { grid-area: main; }
.trio :nth-child(2) { grid-area: top; }
.trio :nth-child(3) { grid-area: bottom; }
the masonry variation with grid-auto-rows

The masonry variation with grid-auto-rows

Masonry keeps each photo’s real proportions and packs them in columns, like a Pinterest board. Grid can fake it with a trick: very short rows, and each item spanning as many rows as its height needs.

.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(100%, 14rem), 1fr));
  grid-auto-rows: 8px;
  column-gap: 1rem;
}
.masonry img { width: 100%; height: auto; display: block; }

Leave out the row gap here and build the spacing into the calculation. A few lines of JavaScript measure each figure and set its span:

const grid = document.querySelector('.masonry');
const ROW = 8, GAP = 16;

function layout(item) {
  const h = item.querySelector('figure').getBoundingClientRect().height;
  item.style.gridRowEnd = 'span ' + Math.ceil((h + GAP) / ROW);
}

const ro = new ResizeObserver(entries => {
  entries.forEach(e => layout(e.target));
});
grid.querySelectorAll(':scope > li').forEach(li => ro.observe(li));

ResizeObserver recalculates each span when an image finishes loading or the window resizes. That solves the most common masonry bug, where tiles overlap because the script ran before the images had a height. The width and height attributes from step 1 help too, since the browser knows each image’s shape early. HTML and CSS gallery grid design is a useful companion to this.

Two alternatives exist.

CSS multi-column layout (column-count: 3 with break-inside: avoid on the figures) needs no script at all, but it orders photos top to bottom, column by column. Readers expect left to right, so newest-first galleries look shuffled.

Browser makers are also working on a native masonry mode for Grid, under the name display: grid-lanes. Check its current support on MDN (Mozilla’s developer documentation) before you rely on it, and keep the JavaScript version as the fallback.

Captions and hover effects that also work on focus

An overlay caption that slides in on hover is a common request. Build it so keyboard users get it too:

.gallery figure { position: relative; overflow: hidden; }
.gallery figcaption {
  position: absolute; inset: auto 0 0 0;
  padding: .5rem .75rem;
  background-color: rgb(0 0 0 / .6);
  color: #fff;
  opacity: 0;
  transition: opacity .2s;
}
.gallery figure:hover figcaption,
.gallery figure:focus-within figcaption { opacity: 1; }
.gallery img { transition: transform .3s; }
.gallery figure:hover img { transform: scale(1.05); }

@media (prefers-reduced-motion: reduce) {
  .gallery img, .gallery figcaption { transition: none; }
}

:focus-within shows the caption when the link inside the figure receives keyboard focus. The prefers-reduced-motion query turns off the zoom for people who asked their operating system to limit animation. Touch screens have no hover, so never hide information a visitor needs inside a hover-only caption. If the caption matters, show it below the image all the time.

The caption’s white text sits on a 60 % black layer. That keeps contrast readable over bright photos, and WCAG 2.1 criterion 1.4.3 sets the minimum contrast at 4.5:1 for normal text.

A lightweight lightbox with the dialog element

The native <dialog> element does most of a lightbox’s hard work. Opened with showModal(), it sits above the page, makes the rest of the page inert, and closes on the Escape key. Add one dialog to the page:

<dialog class="lightbox" aria-label="Image viewer">
  <img alt="">
  <p class="lightbox-caption"></p>
  <button class="prev" aria-label="Previous image">&#8249;</button>
  <button class="next" aria-label="Next image">&#8250;</button>
  <button class="close" aria-label="Close">&times;</button>
</dialog>

Then wire the gallery links to it:

const links = [...document.querySelectorAll('.gallery a')];
const box = document.querySelector('.lightbox');
const big = box.querySelector('img');
const cap = box.querySelector('.lightbox-caption');
let current = 0, opener = null;

function show(i) {
  current = (i + links.length) % links.length;
  const thumb = links[current].querySelector('img');
  big.src = links[current].href;
  big.alt = thumb.alt;
  cap.textContent = links[current].closest('figure')
    .querySelector('figcaption')?.textContent || '';
}

links.forEach((a, i) => a.addEventListener('click', e => {
  e.preventDefault();
  opener = a;
  show(i);
  box.showModal();
}));

box.querySelector('.prev').onclick = () => show(current - 1);
box.querySelector('.next').onclick = () => show(current + 1);
box.querySelector('.close').onclick = () => box.close();
box.addEventListener('keydown', e => {
  if (e.key === 'ArrowLeft') show(current - 1);
  if (e.key === 'ArrowRight') show(current + 1);
});
box.addEventListener('click', e => { if (e.target === box) box.close(); });
box.addEventListener('close', () => opener?.focus());

The last line sends focus back to the thumbnail the visitor clicked, so keyboard users don’t land at the top of the page. The piece CSS Grid Gallery 圖片牆- CSS 教學Tutorial makes a good next read.

A click on the dark backdrop closes the viewer, because that click targets the dialog itself rather than its content. Style the backdrop with the ::backdrop pseudo-element. Inside the dialog, display: flex with justify-content: center and align-items: center centers the photo, while max-width: 90vw and max-height: 85vh keep it inside the viewport. A cursor: zoom-in on the thumbnails tells mouse users that a click opens something.

Can you skip JavaScript entirely? Yes, with the :target method: each thumbnail links to an anchor like #photo-1, and CSS shows the overlay whose id matches the URL.

It works, but it adds an entry to the browser history for every photo, and it doesn’t move focus or handle the Escape key. For a client site, the dialog version is worth its 30 lines. The MDN reference for the dialog element lists every method and event if you want to go further.

performance lazy loading srcset and layout shift

Performance: lazy loading, srcset and layout shift

A gallery is usually the heaviest part of a page, so a few attributes matter more than any CSS trick.

  • loading="lazy" delays off-screen images until the visitor scrolls near them. Leave it off the first row, though. Google’s web.dev guidance warns that lazy-loading the image above the fold delays Largest Contentful Paint (LCP), the moment the main content appears.
  • srcset and sizes let the browser choose a file that matches the tile’s real width. A 14rem thumbnail never needs a 3,000-pixel original.
  • Modern formats such as WebP and AVIF (AV1 Image File Format) usually weigh far less than JPEG (the classic photo format) at similar quality. Serve them through <picture> with a JPEG fallback if you need to support older browsers.
  • width and height attributes reserve the space before each image loads, which prevents the layout from jumping.

Google measures that jumping as Cumulative Layout Shift (CLS). Google’s Core Web Vitals rate a CLS of 0.1 or less as good, and an LCP of 2.5 seconds or less. Both are measured at the 75th percentile of page loads. A srcset for a fluid grid looks like this:

<img src="harbour-600.jpg"
     srcset="harbour-400.jpg 400w, harbour-600.jpg 600w, harbour-900.jpg 900w"
     sizes="(min-width: 64em) 25vw, (min-width: 40em) 50vw, 100vw"
     width="600" height="400" alt="Fishing boats moored in a harbour at dawn" loading="lazy">

Measure the result in PageSpeed Insights or the Lighthouse panel of Chrome DevTools after each change. Field data from real visitors appears in Search Console’s Core Web Vitals report once the page has enough traffic.

Accessibility checks for a gallery

Most of the work is already in the snippets above. A quick pass before launch catches the rest.

  • Every meaningful photo has an alt that describes it. Purely decorative images get alt="".
  • Tab through the gallery: each thumbnail link shows a visible focus ring, as WCAG 2.4.7 (Focus Visible) requires.
  • Open the lightbox with Enter, move with the arrow keys, close with Escape, and check that focus returns to the thumbnail.
  • The visual order matches the HTML order, so no dense packing on content that people read in sequence.
  • Captions that carry information stay visible without hover.

WCAG 2.1.1 (Keyboard) asks that every function work from a keyboard alone. A lightbox that only opens on click fails it, which is one more reason to keep real links in the markup.

a group of three designers collaborating at a table

Common pitfalls, and how to fix them

The grid overflows on small phones. The cause is a fixed minimum such as minmax(250px, 1fr) wider than the screen. Wrap the minimum in min(100%, 250px).

A thin gap appears under every image. Images are inline by default, so they sit on the text baseline and leave room for letter descenders. Set display: block on the img.

Photos look stretched or squashed. You set both a width and a height, or an aspect ratio, without object-fit. Add object-fit: cover, or set height: auto if you want the original shape.

Masonry tiles overlap after the page loads. The spans were calculated before the images had a height. Use the ResizeObserver approach and keep the width and height attributes.

Three photos fill the whole row and look huge. That’s auto-fit stretching the tiles. Switch to auto-fill, or cap the container with a max-width.

Hand-coded gallery or plugin?

The code above weighs a few kilobytes and does exactly what you wrote. A gallery plugin brings ready-made features like albums, filters, sharing buttons and client proofing, but also extra scripts, styles and updates to maintain. On WordPress, the core Gallery block already outputs each photo as a <figure>. You can style it with the same CSS, or add the lightbox script in your theme, without installing anything.

Our view for most agency and portfolio sites: hand-code it. A client gallery rarely needs more than a grid, a featured tile and a viewer, and owning the code means no surprise when a plugin update changes the markup. Reach for a library when the brief includes zooming into high-resolution images, swipe gestures on touch screens, or hundreds of photos with filtering and sorting.

Checklist for your next CSS grid gallery

  1. Markup: list of figures, links to full-size files, alt, width and height.
  2. Columns: repeat(auto-fit or auto-fill, minmax(min(100%, X), 1fr)) and gap.
  3. Thumbnails: display: block, aspect-ratio, object-fit: cover.
  4. Featured items: spans inside a media query, no dense on ordered content.
  5. Masonry, if needed: small grid-auto-rows plus ResizeObserver.
  6. Captions: visible on :focus-within, motion off under prefers-reduced-motion.
  7. Lightbox: <dialog>, arrow keys, focus returned on close.
  8. Performance: no lazy loading on the first row, srcset, WebP or AVIF.
  9. Test: keyboard only, a 320px-wide screen, then Lighthouse.

FAQ

How do I center an image inside a grid cell?

Put place-items: center on the grid container to center every item in its cell, or place-self: center on a single item. To center the whole gallery on the page, give the container a max-width and margin-inline: auto.

Should I use background images instead of img tags?

No, not for content photos. A CSS background image has no alt text, can’t use srcset or native lazy loading, and is invisible to image search. Keep background images for decoration.

Can I add category filters without a library?

Yes. Give each item a data-category attribute and toggle the hidden attribute with a few lines of JavaScript when a filter button is pressed. The grid closes the gaps by itself because hidden items no longer take a cell.

How many images should one gallery page show?

There’s no fixed rule. Our rule of thumb: once a page holds more than a few dozen photos, scrolling and loading start to feel heavy. Beyond that, split the set into albums or add a “load more” button so the page doesn’t keep growing.

Can I use a CSS grid gallery template in WordPress?

Yes. Add the CSS to your child theme or the Additional CSS panel, and target the class of the Gallery block or of a Custom HTML block containing your markup. The lightbox script goes in the theme’s footer or a small code-snippets file.

The quickest way to make this stick is to build it once with your own photos. Start with the HTML and the two-line grid, then add the aspect ratio, and only then the lightbox. Each layer works on its own, so you can stop at any step and still ship a solid gallery.

Building a portfolio or client site? Keep this page bookmarked as your starter kit, and browse our other web design and development guides for the next part of the build.

Recent Posts

No Posts Found!

Categories

Tags

Subscribe

You have been successfully Subscribed! Ops! Something went wrong, please try again.

About Us

Express Jam Studio was founded in 2004 by John Smith. John had previously worked for a courier company, but he saw an opportunity to start his own business in the web design and development industry.

Contact Info

Copyright © 2022 Express Jam Studio. All Rights Reserved.