Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Next.js image gallery is an application UI that you assemble from layout, interaction, and the next/image component. The Image component extends HTML <img> for automatic image optimization; it does not provide a complete gallery, lightbox, filter, keyboard-navigation, or pagination system. Build the gallery shell yourself, then configure each image for the space it actually occupies.

The two decisions with the greatest practical impact are choosing between intrinsic dimensions and fill, and supplying an accurate sizes value. A precise sizes string lets the browser choose an appropriate source from the generated srcset; without it, responsive or fill images are treated as if they occupy the full viewport width.

What the component does—and what your gallery must do

Next.js provides image loading, responsive source generation, optimization, and layout-safety features. Your application still defines the gallery’s columns, gaps, captions, selection state, lightbox, filtering, sorting, pagination, and keyboard behavior. Treat Image as the rendering layer inside a normal React component.

The official Image documentation describes the component as extending HTML <img> for automatic image optimization. That API is sufficient for a grid, masonry-like layout, carousel, or detail view, but there is no dedicated gallery API to turn on.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

A complete responsive gallery component

This App Router example uses a CSS grid and remote image URLs. The wrapper is positioned because fill positions the image absolutely. The aspect ratio establishes the cell geometry before the image arrives.

import Image from 'next/image';
import styles from './Gallery.module.css';

const photos = [
  { id: 'alps', src: 'https://cdn.example.com/gallery/alps.jpg', alt: 'Snowy Alps at sunrise' },
  { id: 'forest', src: 'https://cdn.example.com/gallery/forest.jpg', alt: 'Misty forest trail' },
  { id: 'coast', src: 'https://cdn.example.com/gallery/coast.jpg', alt: 'Rocky coast and blue water' },
  { id: 'desert', src: 'https://cdn.example.com/gallery/desert.jpg', alt: 'Desert dunes in evening light' }
];

export default function Gallery() {
  return (
    <ul className={styles.grid}>
      {photos.map((photo) => (
        <li className={styles.cell} key={photo.id}>
          <Image
            src={photo.src}
            alt={photo.alt}
            fill
            sizes="(min-width: 1200px) 25vw, (min-width: 700px) 33vw, 100vw"
            style={{ objectFit: 'cover' }}
          />
        </li>
      ))}
    </ul>
  );
}
.grid {
  display: grid;
  grid-template-columns: repeat(1, minmax(0, 1fr));
  gap: 1rem;
  list-style: none;
  margin: 0;
  padding: 0;
}

.cell {
  position: relative;
  aspect-ratio: 4 / 3;
  overflow: hidden;
  border-radius: 0.5rem;
}

@media (min-width: 700px) {
  .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}

@media (min-width: 1200px) {
  .grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}

The breakpoints in CSS and sizes must describe the same reality. At widths of at least 1,200 pixels, each image is approximately one quarter of the grid’s content width; between 700 and 1,199 pixels it is about one third; below that it occupies the row. If the grid has a centered max-width, account for that rather than blindly using viewport percentages.

Choose dimensions or fill

Approach Use it when Important details
width and height The source dimensions are known and the image should preserve its natural ratio. These are intrinsic dimensions. CSS can resize the rendered image responsively while the browser reserves the correct aspect-ratio space.
fill The cell controls the shape, such as uniform 4:3 tiles. The parent must be positioned (relative, absolute, or fixed) and have a definite size or aspect ratio.

Intrinsic cards with known source dimensions

<Image
  src="/images/mountain.jpg"
  alt="Mountain ridge"
  width={1600}
  height={1067}
  sizes="(min-width: 900px) 33vw, 100vw"
  style={{ width: '100%', height: 'auto' }}
/>

Use this form for local assets or records that include reliable width and height metadata. The ratio prevents layout shift while the CSS controls the displayed width.

Uniform cropped tiles

With fill, set objectFit: 'cover' when every tile should reach the cell edges, accepting that parts of wide or tall images will be cropped. Use contain when the entire image must remain visible; expect unused space where the aspect ratios differ. A background color on the cell can make that space intentional.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Make sizes match the real layout

sizes is not decorative metadata. Next.js uses it with width-based srcset candidates, and the browser uses it before downloading an image. If it is omitted on a responsive or fill image, the browser assumes 100vw, which can download a much larger file than a one-column fraction requires.

  • Describe the largest rendered width first, using media conditions in descending order.
  • Include grid columns, gaps, container max-width, and side padding in your estimate.
  • Revisit the string when breakpoints or card widths change.
  • Do not preload every tile merely because it is visible in the DOM.

For a two-column layout whose content area is 1,100 pixels wide with a 24-pixel gap, a value near 50vw may overstate the image slightly; a container-relative estimate or a CSS-driven layout may be more accurate. The goal is to select a source close to the actual rendered width, not to produce a mathematically perfect expression for every device.

Allow remote images narrowly

Remote src values are rejected unless their origin is allowed in next.config.js. Define the protocol, hostname, pathname, and query-string rules your gallery actually needs:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'cdn.example.com',
        port: '',
        pathname: '/gallery/**',
        search: ''
      }
    ]
  }
};

module.exports = nextConfig;

Keep each pattern as narrow as possible. Omitted fields imply wildcards, which can admit URLs outside the gallery. The older domains setting lacks protocol, port, and pathname restrictions and has been deprecated since Next.js 14 in favor of remotePatterns. Restart the development server after changing configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Remote metadata and untrusted URLs

For runtime records, store dimensions with each asset or use fill with a controlled wrapper. Do not pass arbitrary user-entered URLs directly to an unrestricted pattern. Validate the host and path at ingestion time, and return a deliberate placeholder when an asset is missing rather than allowing a broken source to disrupt the grid.

Loading, quality, and the LCP image

Preload only a likely LCP image

The current reference lists preload for an image likely to be the largest contentful paint element, generally an above-the-fold hero. A gallery’s first tile may be LCP on one viewport but not another. Do not mark every gallery image as preload; use ordinary loading behavior for below-the-fold items and tune after observing the page.

Quality settings

The documented quality prop accepts values from 1 to 100 and defaults to 75. In Next.js 16, the configured default qualities allowlist is [75] unless you add other permitted values. Check the installed version and your project’s next.config.js before exposing a quality selector or sending another value.

Version-sensitive props

The current documentation marks onLoadingComplete as deprecated. Avoid building new code around it; use supported loading and event patterns for your installed Next.js release, and recheck the Image reference when upgrading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Local versus remote gallery sources

Source Advantages Work required
Local or static import Known at build time; dimensions can be inferred from imported image metadata. Rebuild or redeploy when the asset changes.
Remote CDN or CMS Assets can change without a deployment and can be managed independently. Configure narrow remotePatterns and provide dimensions or a controlled fill wrapper.

Add interaction without coupling it to Image

Keep selection state and controls in a client component while leaving image rendering declarative. For a lightbox, render the selected image in a dialog, trap focus, provide an accessible close button, and support Escape and arrow keys. For filtering or pagination, change the data array before mapping it to Image. These behaviors are application code; the Image component does not implement them.

Accessibility checklist

  • Give every meaningful image specific alternative text; use an empty alt only for purely decorative images.
  • Use buttons for thumbnails that select an image, with an accessible name and an indication of the current item.
  • Do not rely on cropping to communicate information that is absent from the alternative text.
  • Keep focus visible when opening and closing a lightbox.

Troubleshooting common failures

Symptom Likely cause Fix
“Invalid src prop” or an unconfigured-host error The remote URL does not match a pattern exactly. Match protocol, host, path, port, and query rules; restart Next.js after editing config.
Image fills the page or downloads are huge sizes is missing or says 100vw when the card is narrower. Write breakpoint conditions that reflect the actual column width.
Every tile has a different height Intrinsic ratios are being used where a uniform cell was expected. Use a positioned wrapper with aspect-ratio and fill, then choose cover or contain.
Image overlaps content or has zero height The fill parent is not positioned or has no measurable height. Set position: relative and an explicit height or aspect ratio on the wrapper.
Layout shifts while loading No intrinsic dimensions or reserved aspect-ratio space. Pass accurate width/height, or define the wrapper’s aspect ratio before using fill.
Configured quality value is rejected Next.js 16’s allowlist does not include that value. Add the value to the configured allowlist as documented for your version, or use an allowed value.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture the rendered gallery rather than build its UI, ScreenshotNeo returns a screenshot or PDF from one request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the full parameter reference in the ScreenshotNeo documentation. A direct call looks like this:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Every plan includes all features. The free plan provides 1,000 screenshots each month without a card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Does Next.js include a ready-made lightbox?

No. Build or choose a separate React lightbox and pass it the selected image data.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Can I use fill without CSS?

Only if the parent already has a positioned box with a measurable size. In practice, define the wrapper’s position and height or aspect ratio explicitly.

Should every gallery image be preloaded?

No. Reserve preload for a likely LCP image, such as a stable above-the-fold hero; preload status can vary by viewport.

Why does a remote image work in development but fail after deployment?

Compare the deployed URL with the exact remotePatterns protocol, hostname, pathname, port, and query settings. A pattern that matches localhost or a different path will not authorize the production asset.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.