🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Astro Themes••By Komal Nakrani

Build a Photography Portfolio with Astro

Build a fast photography portfolio with Astro: galleries as content collections, responsive AVIF and WebP images, a CSS lightbox, image SEO, and cheap static hosting.

#Astro#Photography Portfolio#Images#Portfolio

To build a photography portfolio with Astro, store each gallery as a folder of original images plus a Markdown file, load them through a content collection with the image() schema helper, render them with <Image /> or <Picture /> from astro:assets so Astro generates resized AVIF and WebP files at build time, and deploy the static output to a CDN. A photography portfolio built with Astro stays fast even with hundreds of photos, because every image is optimized once during the build instead of on each visit.

This guide covers gallery structure, the Astro 7 image settings that matter for photographers, a lightbox without a library, and image SEO.

Key Takeaways

  • Keep high-resolution originals in src/, not public/, so Astro can resize and convert them.
  • Use <Picture formats={['avif', 'webp']} /> for gallery images and set widths and sizes to match your layout.
  • Mark only the first visible image with priority; let the rest lazy-load.
  • Build the lightbox with the native <dialog> element. No library needed.
  • Write descriptive alt text and file names. They are how search engines understand photos.

What a photography portfolio needs

Photographers sell with images, so the site’s job is to get out of their way and load them fast. The page list is short:

Page Purpose
Home A tight selection of your best work, one line on what you shoot, where you work
Galleries One page per series or project
Services or pricing What clients can book, starting prices, what’s included
About Your story, a portrait, clients or publications
Journal Behind-the-scenes posts, shoot stories, location guides
Contact Enquiry form with date, location and shoot type

Resist the urge to show everything. Twelve strong images per gallery beat sixty average ones, and the page loads faster.

Create the project

# Terminal
npm create astro@latest photo-portfolio
cd photo-portfolio
npm run dev

Astro uses Sharp for image processing, which Astro lists as an optional dependency, so npm usually installs it for you. If the build reports that Sharp is missing, install it with npm install sharp.

Prefer a finished layout? The Astro portfolio and agency themes category includes photography-specific designs such as Aerials, a minimal template for photographers with project pages, and Different Studios, which has several portfolio layouts. On the free side, Astro’s official portfolio starter is a clean base, and the astro.build/themes directory lists community gallery templates worth comparing.

Organize galleries as content

Put each gallery in its own folder with the photos next to its Markdown file. This keeps relative image paths simple and makes adding a gallery a copy-and-rename job.

src/content/galleries/
  iceland-coast/
    index.md
    01-black-sand.jpg
    02-sea-stacks.jpg
    03-glacier-lagoon.jpg
  city-nights/
    index.md
    01-tram.jpg

Then describe the collection:

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const galleries = defineCollection({
  loader: glob({ pattern: '**/index.md', base: './src/content/galleries' }),
  schema: ({ image }) =>
    z.object({
      title: z.string(),
      description: z.string().max(160),
      date: z.coerce.date(),
      location: z.string().optional(),
      cover: image(),
      photos: z.array(
        z.object({
          src: image(),
          alt: z.string().min(10),
          caption: z.string().optional(),
        }),
      ),
    }),
});

export const collections = { galleries };

The alt: z.string().min(10) rule stops placeholder text like “photo” from slipping through. A gallery file:

---
# src/content/galleries/iceland-coast/index.md
title: "Iceland coast"
description: "Black sand, basalt stacks and glacier ice along Iceland's south coast in winter light."
date: 2026-02-14
location: "Vík and Jökulsárlón, Iceland"
cover: "./01-black-sand.jpg"
photos:
  - src: "./01-black-sand.jpg"
    alt: "Waves washing over black sand beach under low winter sun"
  - src: "./02-sea-stacks.jpg"
    alt: "Basalt sea stacks rising from rough grey water off Reynisfjara"
    caption: "Reynisdrangar at 11am, the sun barely above the horizon."
  - src: "./03-glacier-lagoon.jpg"
    alt: "Blue icebergs floating in a glacier lagoon at dusk"
---

Shot over five days in February.

With the glob() loader, each entry’s ID comes from its path, so iceland-coast/index.md becomes the ID iceland-coast. The content collections guide explains IDs and loaders in more detail.

Render galleries with optimized images

---
// src/pages/galleries/[id].astro
import { getCollection, render } from 'astro:content';
import { Picture } from 'astro:assets';
import BaseLayout from '../../layouts/BaseLayout.astro';

export async function getStaticPaths() {
  const galleries = await getCollection('galleries');
  return galleries.map((g) => ({ params: { id: g.id }, props: { gallery: g } }));
}

const { gallery } = Astro.props;
const { Content } = await render(gallery);
---
<BaseLayout title={gallery.data.title} description={gallery.data.description}>
  <h1>{gallery.data.title}</h1>
  {gallery.data.location && <p>{gallery.data.location}</p>}
  <Content />
  <ul class="gallery">
    {gallery.data.photos.map((photo, i) => (
      <li>
        <button type="button" class="open" data-index={i} aria-label={`Open: ${photo.alt}`}>
          <Picture
            src={photo.src}
            alt={photo.alt}
            formats={['avif', 'webp']}
            widths={[400, 800, 1200]}
            sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
            quality={80}
            priority={i === 0}
          />
        </button>
        {photo.caption && <p class="caption">{photo.caption}</p>}
      </li>
    ))}
  </ul>
</BaseLayout>

What each option does:

  • formats={['avif', 'webp']} writes a <picture> element with AVIF first, WebP as fallback, and the original format as a last resort.
  • widths and sizes produce a srcset so phones download a 400px file while large screens get 1200px.
  • quality={80} is a sensible default for photos. Push it higher for galleries where fine detail is the point.
  • priority on the first image loads it eagerly with high fetch priority, which helps Largest Contentful Paint. Every other image lazy-loads.

The build is slower with many photos, since every size and format is generated, but it happens once. Astro caches processed images between builds, and most CI hosts can keep that cache. The Astro image cheatsheet lists every prop, and the official images guide covers image services.

A lightbox with the native dialog element

A lightbox needs to show one large image, move between photos, and close with Escape. The <dialog> element handles focus trapping and Escape for you.

---
// src/components/Lightbox.astro
import { getImage } from 'astro:assets';
const { photos } = Astro.props;
const large = await Promise.all(
  photos.map((p) => getImage({ src: p.src, width: 2000, format: 'webp', quality: 85 })),
);
---
<dialog id="lightbox" aria-label="Photo viewer">
  <img alt="" />
  <button type="button" data-step="-1" aria-label="Previous photo">‹</button>
  <button type="button" data-step="1" aria-label="Next photo">›</button>
  <form method="dialog"><button aria-label="Close">×</button></form>
</dialog>

<script is:inline define:vars={{ items: large.map((img, i) => ({ src: img.src, alt: photos[i].alt })) }}>
  const dialog = document.getElementById('lightbox');
  const img = dialog.querySelector('img');
  let current = 0;
  const show = (i) => {
    current = (i + items.length) % items.length;
    img.src = items[current].src;
    img.alt = items[current].alt;
  };
  document.querySelectorAll('.open').forEach((btn) =>
    btn.addEventListener('click', () => { show(Number(btn.dataset.index)); dialog.showModal(); }),
  );
  dialog.querySelectorAll('[data-step]').forEach((btn) =>
    btn.addEventListener('click', () => show(current + Number(btn.dataset.step))),
  );
  dialog.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowRight') show(current + 1);
    if (e.key === 'ArrowLeft') show(current - 1);
  });
</script>

Drop <Lightbox photos={gallery.data.photos} /> into the gallery page. getImage() creates the large versions at build time, so the full-size file only downloads when someone opens it. For a deeper version with captions and swipe support, see the image lightbox component.

Image SEO for photographers

Search engines can’t see your photos the way people do. They read text around them:

  1. Alt text that describes what’s in the frame, not “IMG_4021”.
  2. File names with words: glacier-lagoon-dusk.jpg beats DSC_0042.jpg. Astro keeps the original name as part of the output file name.
  3. A paragraph per gallery describing the series, location and context.
  4. Structured data: an ImageGallery on gallery pages, with creator pointing to you as a Person, helps search engines attribute the work.
  5. A sitemap with npx astro add sitemap so every gallery gets discovered.

If you shoot locally (weddings, portraits, events), add your city and region to the home page and about page in plain text. People search “family photographer in Leeds”, not “photographer”.

Protect your work without breaking the site

Right-click blockers annoy visitors and stop no one. Better options:

  • Publish web-sized images only. The largest file you serve is 2000px wide in the example above; your originals never leave src/.
  • Add a copyright line and licensing contact on the about page.
  • Consider a subtle watermark on images that are likely to be shared without credit.

Check what metadata ends up in your output files. Camera EXIF can include GPS coordinates, which matters for photos taken at clients’ homes. Strip location data in your editing software when you export, so it never reaches the repo.

Deploy and keep builds fast

Run npm run build and deploy dist/ to Cloudflare Pages, Netlify or Vercel. Photo-heavy sites have one specific consideration: build time grows with the number of images and sizes. Keep it manageable by:

  • Exporting originals at around 3000px on the long edge rather than full camera resolution.
  • Using two or three widths, not eight.
  • Enabling your host’s build cache so processed images are reused.

The deploy to Cloudflare Pages docs cover setup, and the CI build cache tip shows how to keep the image cache between builds.

FAQ

Is Astro good for a photography portfolio?

Yes. Astro resizes and converts photos to AVIF and WebP at build time, generates responsive srcset attributes, and lazy-loads images by default, so large galleries load quickly. It ships no JavaScript unless you add it, which keeps the focus on the photos.

How do I add image galleries in Astro?

Create a content collection where each gallery has a Markdown file listing its photos with the image() schema helper, store the photos next to it in src/content/, and render them with <Image /> or <Picture /> from astro:assets on a dynamic route.

Should I put photos in src or public in Astro?

Put photos in src/ if you want Astro to optimize them; images in src/ are resized, converted and fingerprinted at build time. Files in public/ are copied as they are, so only use it for images you have already optimized or that must keep an exact URL.

What image format should a photography website use?

Serve AVIF with a WebP fallback using <Picture formats={['avif', 'webp']} />. AVIF usually gives the smallest files at the same visual quality, and WebP covers browsers that don’t support AVIF. Keep your originals as high-quality JPEGs in the repo.

How do I make an Astro photo portfolio load faster?

Set accurate widths and sizes so devices download the right size, mark only the first visible photo with priority, keep gallery pages to a focused selection, and avoid loading a full-size image until someone opens it in the lightbox.