Web Design Tutorials

How to Add an Image Gallery to Your Website

Written by Muhammad Naeem15 min readUpdated for 2026
A vibrant collage of travel photographs arranged like a gallery wall
A vibrant collage of travel photographs arranged like a gallery wall. Stock photo by Taryn Elliott on Pexels (photo 4340918, free to use under the Pexels licence).

A single photo can say a lot, but a gallery tells the whole story. Whether you run a photography portfolio, a restaurant, a real estate listing, a product page, or a travel blog, an image gallery lets visitors browse your work without leaving the page. In this guide you will learn how to add an image gallery to your website from scratch — a clean HTML and CSS grid, a lightbox for full-size viewing, captions, lazy loading, and the performance habits that keep it fast. You will also see how the same result is done in WordPress and popular website builders, so you can pick the route that fits your site.

What Is an Image Gallery — and When Do You Need One?

An image gallery is a group of photos displayed together in a tidy grid or slider, usually with the option to click any photo to see it larger. It is one of the most common features on the modern web, and for good reason: visitors understand pictures faster than paragraphs, and a gallery keeps them exploring instead of scrolling past a long wall of text.

You probably need a gallery if any of these sound familiar. A photographer or designer wants to show a portfolio. A restaurant wants to show its food and dining room. A hotel or guesthouse wants to show its rooms. A shop wants to show a product from several angles. A builder or contractor wants to show before-and-after work. A travel blogger wants to share a trip in pictures. In each case, the gallery does the selling while the text explains the details.

A gallery is not the right tool for every page, though. If you only have one or two photos, place them in the article normally — a gallery with two images looks empty. And if your images are decorative rather than informative, a simple row of photos may serve better than a full gallery with a lightbox. The rule is simple: build a gallery when the photos themselves are the content your visitors came to see.

Plan Your Gallery Before You Write Any Code

The best galleries are planned before a single line of code is written. A few minutes of planning saves hours of rearranging later, and it keeps the finished gallery looking deliberate instead of thrown together.

Start by choosing the photos. Pick your strongest images and leave the rest out — ten excellent photos beat thirty average ones every time. If the photos come from different shoots, check that they look consistent: similar lighting, similar colours, and the same general mood. A gallery that jumps between dark and bright, warm and cold, feels messy even when every photo is good on its own.

Next, decide the order. Put your single best photo first, because it sets the expectation for everything after it. Then arrange the rest so the story flows — for a restaurant, that might be the dining room, then the food, then the desserts; for a project portfolio, the finished result first, then the process shots. Avoid grouping all the similar photos together; spread them out so the gallery keeps surprising the eye.

Then settle the technical details. Use the same aspect ratio for every thumbnail so the grid lines up neatly — a common choice is 4:3 or 3:2 for photos, or 1:1 squares for a bold, uniform look. Prepare two versions of each photo: a small thumbnail for the grid and a larger version for the lightbox. Finally, write a short caption for each photo before you build. Captions are easy to forget and hard to add later, and they make a gallery far more useful, especially for portfolios and product pages.

  • Choose 6–12 photos for a first gallery — enough to feel complete, few enough to stay fast.
  • Keep one aspect ratio across all thumbnails so the grid stays aligned.
  • Prepare two sizes: a thumbnail (around 600px wide) and a full-size version (around 1600px wide).
  • Write captions first — one short sentence per photo is enough.
  • Use your own photos or properly licensed stock — never take images from other websites without permission.

Build a Simple Gallery With HTML and CSS Grid

The simplest reliable gallery is a grid of images built with plain HTML and CSS. It needs no plugin, no JavaScript framework, and it works in every modern browser. CSS Grid does the heavy lifting: it arranges the photos into neat rows and columns and reflows them automatically when the screen gets smaller.

The HTML is a container with one figure per photo. Each figure holds an image and a caption. The alt text describes the photo for screen readers and search engines — write real descriptions, not file names.

<div class="gallery">
  <figure>
    <img src="images/photo-1.jpg" alt="Dining room of the restaurant at sunset">
    <figcaption>The dining room at sunset</figcaption>
  </figure>
  <figure>
    <img src="images/photo-2.jpg" alt="Chef plating the signature dish">
    <figcaption>Our signature dish, plated fresh</figcaption>
  </figure>
  <!-- Repeat one figure per photo -->
</div>

The CSS turns that list of figures into a responsive grid. The key line is grid-template-columns with auto-fill and minmax: it fits as many columns as the screen allows, each at least 250 pixels wide, and stretches them to fill the row. The gap property adds breathing room between photos, and object-fit: cover keeps every thumbnail the same height without stretching the image.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}
.gallery figure {
  margin: 0;
  overflow: hidden;
  border-radius: 12px;
}
.gallery img {
  width: 100%;
  height: 220px;
  object-fit: cover;
  display: block;
  transition: transform 0.3s ease;
}
.gallery img:hover {
  transform: scale(1.05);
}
.gallery figcaption {
  font-size: 0.85rem;
  color: #666;
  padding: 0.5rem 0.25rem;
}

The small hover effect — a gentle zoom when the mouse passes over a photo — costs almost nothing and makes the gallery feel alive. Keep it subtle: a scale of 1.03 to 1.06 is enough. Anything stronger looks jumpy and distracts from the photos themselves.

If you want a more dramatic layout, try a masonry-style gallery where photos keep their natural heights instead of being cropped to one height. CSS columns make this easy: set column-count on the container and give each figure a bottom margin. The result looks like a Pinterest board. The trade-off is that the order reads down each column rather than across rows, which can feel odd for a step-by-step story, so use masonry for collections and a strict grid for sequences.

Add a Lightbox So Visitors Can View Photos Full-Size

A grid shows the whole collection at a glance, but thumbnails are too small for detail. A lightbox fixes that: when a visitor clicks a photo, it opens large in an overlay that darkens the rest of the page, with controls to move to the next or previous photo and a close button. It is the feature that turns a nice grid into a proper gallery.

You do not need a heavy plugin for this. A small amount of JavaScript — under fifty lines — gives you a working lightbox with keyboard support. The idea is simple: each thumbnail links to its full-size image, and a click opens that image inside a fixed overlay element. The Escape key and a click on the dark background both close it, and the arrow keys move between photos.

First, wrap each thumbnail in a link to the full-size image and add a data attribute with the caption. Then add one overlay element at the end of your page — a single div that stays hidden until it is needed.

<div class="gallery">
  <a href="images/photo-1-large.jpg" class="gallery-item"
     data-caption="The dining room at sunset">
    <img src="images/photo-1.jpg" alt="Dining room of the restaurant at sunset">
  </a>
  <!-- More items -->
</div>

<div id="lightbox" class="lightbox" hidden>
  <button id="lightbox-close" aria-label="Close gallery">&times;</button>
  <button id="lightbox-prev" aria-label="Previous photo">‹</button>
  <img id="lightbox-img" src="" alt="">
  <p id="lightbox-caption"></p>
  <button id="lightbox-next" aria-label="Next photo">›</button>
</div>

The JavaScript collects all the gallery links, tracks which one is open, and swaps the image when the visitor clicks next or previous. Because the overlay is a single element reused for every photo, the code stays short and the page stays light.

const items = [...document.querySelectorAll('.gallery-item')];
const box = document.getElementById('lightbox');
const boxImg = document.getElementById('lightbox-img');
const boxCaption = document.getElementById('lightbox-caption');
let current = 0;

function openBox(index) {
  current = index;
  boxImg.src = items[current].href;
  boxImg.alt = items[current].querySelector('img').alt;
  boxCaption.textContent = items[current].dataset.caption || '';
  box.hidden = false;
  document.body.style.overflow = 'hidden';
}
function closeBox() {
  box.hidden = true;
  document.body.style.overflow = '';
}
items.forEach((item, i) => {
  item.addEventListener('click', (e) => { e.preventDefault(); openBox(i); });
});
document.getElementById('lightbox-close').addEventListener('click', closeBox);
document.getElementById('lightbox-next').addEventListener('click', () => openBox((current + 1) % items.length));
document.getElementById('lightbox-prev').addEventListener('click', () => openBox((current - 1 + items.length) % items.length));
document.addEventListener('keydown', (e) => {
  if (box.hidden) return;
  if (e.key === 'Escape') closeBox();
  if (e.key === 'ArrowRight') openBox((current + 1) % items.length);
  if (e.key === 'ArrowLeft') openBox((current - 1 + items.length) % items.length);
});

A few details make the lightbox feel professional. Prevent the page behind it from scrolling while it is open — the code above does this by setting body overflow to hidden. Give every button an aria-label so screen-reader users know what it does. And preload the next image quietly in the background so moving through the gallery feels instant instead of laggy. If writing this yourself feels like too much, well-maintained lightbox libraries exist that do the same job with one line of setup — just check that the library is still updated and does not pull in a large framework you do not need.

Make the Gallery Responsive on Phones and Tablets

More than half of most websites' visitors arrive on a phone, so a gallery that only looks good on a desktop is a gallery that fails most of its audience. The CSS Grid approach above is already responsive — auto-fill drops columns as the screen narrows — but a few extra touches make the mobile experience genuinely good instead of merely acceptable.

On small screens, reduce the minimum column width so two photos still fit side by side on a phone in portrait, or let the gallery fall to a single column if your photos are tall. A single column is not a failure — for portrait photos it often looks better than two cramped columns. Add a media query that adjusts the gap and the thumbnail height for small screens, and test it at 360 pixels wide, which is a common budget-phone width.

@media (max-width: 600px) {
  .gallery {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 10px;
  }
  .gallery img {
    height: 160px;
  }
}

The lightbox needs mobile attention too. On a phone there is no keyboard, so the previous and next buttons must be large enough to tap — at least 44 pixels across — and placed where a thumb can reach them. Swipe gestures are a nice bonus if your lightbox library supports them, but big tap targets are the essential part. Also make sure the lightbox image never overflows the screen: set its max-width to 100% and its max-height to about 85% of the viewport, and let the caption sit below it instead of overlapping.

Finally, test the gallery on a real phone, not just a resized desktop browser. Touch targets, pinch-to-zoom behaviour, and the way the lightbox feels under a thumb are things a desktop preview cannot show you. Open the page, tap through every photo, and check that nothing requires a precise mouse click.

Captions, Alt Text and Accessibility

A gallery without captions and alt text is a gallery that excludes people — and search engines. Alt text is what screen readers announce to blind visitors, and it is also what Google reads when it decides what your images show. A caption is what sighted visitors read under the photo. They serve different readers, so they should say different things: the alt text describes the image itself, while the caption adds context, like a name, a date, or a price.

Write alt text as a plain sentence. Good: alt="White wedding dress with lace sleeves on a mannequin in a bridal shop window". Bad: alt="IMG_4821.jpg" or alt="image". If a photo is purely decorative — a background texture, for example — an empty alt attribute (alt="") is correct, because it tells screen readers to skip it. But gallery photos are the content, so they almost always deserve real alt text.

Accessibility goes beyond alt text. Make sure every gallery control works from a keyboard: a visitor should be able to tab to a thumbnail, press Enter to open it, use the arrow keys to move through the lightbox, and press Escape to close it. The example lightbox above already supports this. Also check colour contrast on captions and buttons, and never rely on colour alone to communicate anything — a "new" badge in red means nothing to a visitor who cannot see red.

There is a search benefit here too. Google Images can send real traffic to a gallery page when the images are properly described, and a page with well-written alt text and captions is easier for search engines to understand than a page of nameless photos. Treat image SEO as part of the build, not an afterthought.

Speed It Up: Lazy Loading and Image Optimisation

Galleries are the easiest way to accidentally make a website slow. Ten photos at two megabytes each is twenty megabytes of downloads before the visitor has seen anything — enough to make a mobile visitor leave before the page finishes loading. Speed is not a nice extra for galleries; it is the difference between a gallery that gets viewed and one that gets abandoned.

The single most effective change is lazy loading. By default, a browser downloads every image on the page as soon as it loads, even the ones far below the fold. Adding loading="lazy" to each thumbnail tells the browser to wait until the visitor scrolls near the photo. It is one attribute, it works in all modern browsers, and it can cut the initial page weight by most of the gallery's total size.

<img src="images/photo-1.jpg" alt="Dining room of the restaurant at sunset" loading="lazy" width="600" height="400">

Always include width and height attributes on your images. Without them, the browser does not know how much space to reserve, so the page jumps around as each photo loads — a problem called layout shift that frustrates visitors and hurts search rankings. With the dimensions in place, the layout stays stable while the photos load in.

Then optimise the files themselves. Resize each photo to the largest size it will actually be shown — there is no point serving a 6000-pixel-wide photo as a 250-pixel thumbnail. Save photos as WebP where your tools support it; it typically produces much smaller files than JPEG at the same visible quality. Aim for thumbnails under 100KB each and full-size lightbox images under 500KB. Free tools like Squoosh can compress a whole folder of images in minutes, and the quality difference at normal viewing sizes is invisible.

For larger galleries, consider responsive images with srcset, which lets the browser pick the right file size for the visitor's screen instead of sending the same large file to every device. A phone on mobile data gets the small version; a desktop on broadband gets the large one. It takes a little more markup, but for galleries with dozens of photos it is worth the effort.

  • Lazy-load every thumbnail below the first row with loading="lazy".
  • Always set width and height to prevent the page jumping as images load.
  • Serve WebP where possible, with JPEG as a fallback for very old browsers.
  • Keep thumbnails small — resize to the size they are actually displayed at.
  • Test on a slow connection before you call the gallery finished.

Adding a Gallery in WordPress and Website Builders

Not every website is built by hand, and that is fine. If your site runs on WordPress or a builder like Wix or Squarespace, you can add a gallery without writing any code at all — the platform provides the grid, the lightbox, and the responsive behaviour out of the box.

In WordPress, the built-in Gallery block is the starting point. Add the block, upload or select your photos, and choose the number of columns. WordPress creates the grid, crops the thumbnails, and opens a lightbox when a photo is clicked if you enable the "link to media file" option or use the lightbox setting in newer versions. For more control — masonry layouts, filters by category, or albums — gallery plugins add those features, but check the plugin's reviews and update history before installing it, and keep the number of plugins low so the site stays fast.

In Wix, Squarespace, and similar builders, galleries are ready-made elements you drag onto the page. Pick a layout — grid, slider, or slideshow — drop in your photos, and the builder handles responsiveness and the lightbox. The trade-off is flexibility: you get what the builder offers, and custom behaviour like a filtered gallery by category may need a paid plan or a workaround. For most small business sites, though, the built-in gallery is more than enough.

Whichever platform you use, the planning advice from earlier still applies. A builder cannot fix a gallery of thirty unedited photos with no captions. Choose the photos, write the captions, and optimise the files first — then the platform's gallery tool will do the rest well.

Common Image Gallery Mistakes to Avoid

Most gallery problems are avoidable, and they tend to be the same handful of mistakes repeated on site after site. Check your gallery against this list before you publish.

Too many photos. A gallery of fifty images feels like a chore, not a showcase. Visitors rarely scroll past the first dozen. Curate hard, and if you truly have more to show, split the gallery into albums or categories instead of one endless grid.

Full-size files as thumbnails. Linking the grid directly to the original camera files — several megabytes each — is the most common performance mistake. Always create real thumbnails and lazy-load them.

No captions or alt text. A grid of nameless photos tells visitors nothing and tells Google nothing. One sentence per photo is enough, but zero is a missed opportunity.

A lightbox with no way out. Every lightbox needs a visible close button, an Escape-key handler, and a click-on-background-to-close behaviour. A visitor who feels trapped inside an overlay will close the whole tab instead.

Ignoring mobile. A gallery that looks perfect on a desktop and breaks on a phone fails most of its visitors. Test on a real phone, check the tap targets, and make sure the lightbox image fits the screen.

Using other people's photos. Images found through a search engine are not free to use. Use your own photos or properly licensed stock, and keep a note of where each photo came from.

Auto-playing sliders with no pause button. If you use a slideshow instead of a grid, give visitors control. An auto-advancing gallery that cannot be paused is annoying and inaccessible.

Conclusion

Adding an image gallery to your website is one of the highest-impact upgrades you can make, and it does not need a plugin or a framework. A CSS Grid layout, a small lightbox script, real captions and alt text, and properly optimised images will give you a gallery that looks good, loads fast, and works for every visitor — on desktop and on mobile. Plan the photos first, keep the grid tidy, lazy-load the thumbnails, and test the result on a real phone before you publish. If you would like help adding a gallery — or any other feature — to your own website, get in touch and we will build it for you.

Frequently Asked Questions

How many photos should an image gallery have?

For most pages, 6 to 12 photos is the sweet spot — enough to feel complete without overwhelming visitors or slowing the page. If you have more to show, split the photos into albums or categories instead of one long grid.

Do I need a plugin to add an image gallery?

No. A simple gallery can be built with plain HTML and CSS Grid, and a lightbox needs only a small amount of JavaScript. Plugins and builders are convenient, but they are optional — the hand-built route gives you full control and keeps the page light.

What image size should gallery thumbnails be?

Thumbnails around 600 pixels wide are usually enough for a grid, since they are displayed at roughly 250 to 400 pixels. Keep each thumbnail under about 100KB by saving it as WebP or a well-compressed JPEG, and keep the full-size lightbox version under about 500KB.

How do I make an image gallery load faster?

Lazy-load the thumbnails with loading="lazy", serve properly sized images instead of full camera files, use the WebP format, and add width and height attributes so the page layout does not jump as photos load. These four steps cover most gallery performance problems.

What is a lightbox in an image gallery?

A lightbox is an overlay that opens when a visitor clicks a photo, showing it large against a darkened background with controls to move to the next or previous image and to close it. It lets visitors inspect details without leaving the page.

Can I add an image gallery in WordPress without code?

Yes. WordPress has a built-in Gallery block: add it, select your photos, choose the number of columns, and it creates a responsive grid with an optional lightbox. Gallery plugins add extra layouts like masonry or filtered albums if you need them.

Want a Gallery on Your Website?

We build fast, beautiful galleries and complete websites for small businesses. Tell us about your project and we will get back to you with a clear plan.

WhatsApp: 03207140898Send Email Inquiry

Explore More Resources & Services:

How to Speed Up Your WordPress WebsiteWebsite Navigation Best PracticesOn-Page SEO GuideHow to Add a Blog to Your WebsiteHow to Add a Sitemap to Your WebsiteHow to Add Live Chat to Your Website
Chat with Naeem