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 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 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
Build a CSS Grid Image Gallery With Masonry and a Lightbox Read More »
