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

Use CSS Grid to fit as many gallery items as the available width allows, then give each image a consistent frame and choose whether it should crop or remain fully visible. For a production gallery, also provide intrinsic image dimensions, useful alternative text, and appropriately sized image files. The complete example below is a starting point you can adapt to your own images and layout.

Build the gallery layout with CSS Grid

A responsive gallery needs to solve two separate problems: how the cards arrange themselves as the viewport changes, and how each image fits inside its card. CSS Grid handles the arrangement. Image sizing and cropping rules handle the frame.

This example uses an automatically fitting grid. The browser creates as many columns as fit while keeping each card at least 15rem wide where possible. If the available space is narrower than that minimum, the min(100%, 15rem) expression lets a card shrink to the container width rather than overflow it.

<div class="gallery">
  <img src="images/lake-800.jpg"
       srcset="images/lake-400.jpg 400w, images/lake-800.jpg 800w"
       sizes="(max-width: 600px) 100vw, 33vw"
       width="800" height="600"
       alt="A kayaker crossing a calm lake">

  <img src="images/forest-800.jpg"
       srcset="images/forest-400.jpg 400w, images/forest-800.jpg 800w"
       sizes="(max-width: 600px) 100vw, 33vw"
       width="800" height="600"
       alt="Sunlight filtering through a forest">

  <img src="images/coast-800.jpg"
       srcset="images/coast-400.jpg 400w, images/coast-800.jpg 800w"
       sizes="(max-width: 600px) 100vw, 33vw"
       width="800" height="600"
       alt="Waves breaking along a rocky coast">
</div>
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
  gap: 1rem;
}

.gallery img {
  display: block;
  width: 100%;
  aspect-ratio: 4 / 3;
  object-fit: cover;
}

Replace the sample paths with files that exist in your project. The width and height attributes should describe the source image’s intrinsic dimensions, not an arbitrary display size. The CSS sets a 4:3 display frame; the browser can reserve space from the supplied dimensions while the file loads, and the CSS ratio controls the rendered frame.

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.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Adjust the minimum card width

The 15rem value is a design choice, not a universal breakpoint. Raise it if captions or controls need more room; lower it if narrow cards still work for your content. With auto-fit, the grid fits as many columns as it can at that minimum and expands the tracks to use available space.

If you need a fixed number of columns at defined widths, use media queries instead. For example, a design could declare one column by default and add two or three columns at chosen minimum viewport widths. Those breakpoints should reflect when the cards become cramped or overly wide in your actual layout, not a presumed device category.

Keep thumbnails consistent without distorting images

Set the image width to fill its grid item and define a frame ratio with aspect-ratio. Then select how the source image behaves in that frame:

  • object-fit: cover fills the frame and crops the part that does not fit. This creates uniform thumbnail shapes, but important content near the edges can be cut off.
  • object-fit: contain keeps the entire image visible. Depending on the source and frame ratios, empty space may remain around the image.

Use object-position when a cover crop should favor a particular part of an image. For example, object-position: center top keeps the upper area centered in the visible crop. A shared crop is not always appropriate: portraits, maps, diagrams, and product details may need different framing or no crop at all.

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

If every source image has a different shape and you want to preserve those shapes, remove the shared aspect-ratio frame and let the images keep their intrinsic ratios. The result will not have perfectly aligned thumbnail rows, but no image content needs to be cropped merely to make the grid uniform.

Use responsive image files, not just a responsive layout

CSS changes the gallery’s arrangement; it does not automatically choose a smaller image file for a small rendered card. The srcset and sizes attributes provide the browser with candidates and a description of the image’s expected rendered width. The browser can then select an appropriate resource for the layout and device conditions.

In the sample, srcset offers 400- and 800-pixel-wide versions of the same image. The sizes value says that the image is expected to occupy the viewport width up to 600 pixels, and about a third of the viewport at larger widths. This is only a representative expression. Change it to reflect the gallery’s actual container, gaps, and column count; if the gallery is inside a narrow page column, using viewport-wide estimates may not describe its rendered size accurately.

Provide a normal src as the fallback. Make sure the files named in srcset are real variants of the same visual image and that their width descriptors correspond to their actual widths. Responsive image selection is distinct from art direction: for the same image at different resolutions use srcset with sizes; when the composition or crop itself should change at different sizes, use a picture element with media-qualified source elements and retain an img child with src and alt as the fallback.

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

Write useful alt text and reserve layout space

For an informative image, write concise alternative text that communicates the relevant content. Do not use a filename or repeat nearby caption text unless it adds needed context. For an image that is purely decorative and contributes no information, use an empty attribute: alt="".

MDN describes the alt attribute as a textual replacement for an image that screen readers read so users know what the image means. Supplying alternative text is part of making the gallery’s content available to people who do not see the images; it is not a styling choice.

Include intrinsic width and height values on each image. They help the browser establish image proportions and reserve layout space before image bytes arrive, reducing unexpected movement as the gallery loads. If CSS imposes a different display ratio, make that ratio explicit with the frame styling, as in the example.

Load images below the fold thoughtfully

For images that are well below the initially visible part of the page, loading="lazy" can defer loading until they are near the viewport. Add it to those images as needed:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<img src="images/forest-800.jpg"
     width="800" height="600"
     loading="eager"
     alt="Sunlight filtering through a forest">

Keep dimensions on lazy-loaded images so the browser can reserve their space before they load. Avoid applying lazy loading indiscriminately to an image that needs to appear immediately at the top of the page; deferring an immediately visible image can delay its display. Choose loading behavior based on where each image sits in the page rather than treating every gallery item identically.

Choose the gallery behavior that suits the images

Decision Use this when Trade-off
Flexible columns with auto-fit You want the number of columns to follow available container width with few explicit breakpoints. The column count follows the minimum card width and available space; check the result at narrow and wide sizes.
Fixed column counts at breakpoints The design requires a deliberate number of columns at particular layout widths. You must choose and maintain breakpoints that fit the real content.
Uniform thumbnails with cover Consistent frames and aligned gallery rows matter more than showing every edge of every source. The crop can hide meaningful details; adjust positioning or use a different treatment for those images.
Full image with contain or intrinsic ratios Showing the complete image is more important than identical thumbnail crops. Frames may show empty space, or gallery rows may not align evenly.
srcset and sizes The visual image stays the same while the browser can choose among resolutions. The candidates and size hint must match real files and the actual rendered layout.
picture with media-qualified sources The crop or composition should differ by layout condition. You need appropriate art-directed alternatives as well as a fallback image.
Lazy loading An image is outside the initial visible area and can wait until the reader approaches it. Do not defer an image that should be visible immediately; dimensions remain important.

Troubleshoot common gallery problems

The gallery overflows on a narrow screen

Check that the grid’s minimum track can shrink to the container width. The example uses minmax(min(100%, 15rem), 1fr) for that reason. Also inspect the gallery’s parent for a fixed width, excessive padding, or another element forcing a wider minimum size.

Images look stretched

Do not set both image dimensions to arbitrary values without a fitting rule. Use width: 100% with a frame ratio and object-fit: cover or contain. These fit the source into a frame without changing its proportions.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

A crop hides the subject

Change object-position to move the visible crop, use contain to show the complete image, or avoid a common ratio for that item. If a different composition is genuinely needed at a layout size, provide an art-directed source with picture.

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

The browser loads an unexpectedly large image

Verify that each srcset width descriptor matches the file’s actual pixel width and that sizes describes the image’s rendered width in the gallery. A viewport-based estimate can be wrong when the gallery sits in a constrained content column or when the columns do not match the estimate.

The page shifts while images load

Add correct intrinsic width and height attributes, and ensure the CSS frame ratio is intentional. For images loaded lazily, dimensions are especially useful because the browser needs to reserve their space before fetching them.

A screen reader announces an unhelpful image name

Replace filename-like or generic alternative text with a concise description of the image’s relevant information. If the image is decorative, use alt="" instead of omitting the attribute or describing irrelevant visual details.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check the result at real content widths

  1. Open the page in a browser and inspect the gallery at the narrowest width your layout supports.
  2. Resize the viewport across the widths where the column count changes. Confirm that cards neither overflow nor become too narrow for their content.
  3. Inspect a variety of source images, especially wide, tall, and subject-near-the-edge images. Verify that the selected crop preserves the content that matters.
  4. Check that every source path and responsive candidate loads, and that the displayed image dimensions follow the intended frame.
  5. Review alternative text and loading behavior: informative images need meaningful text, decorative images need empty alt text, and immediately visible images should not be delayed without reason.

These checks validate your own markup and assets; the CSS pattern is illustrative rather than a claim that one set of widths or crops suits every gallery.

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

Or skip the browser setup

If you need a clean screenshot of a gallery page for a visual check or documentation, ScreenshotNeo offers a one-request screenshot API. For example, cURL can save a WebP capture of a page:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Replace https://stripe.com with the page you want to capture and set your API key. The API can return PNG, JPEG, WebP, or PDF; see the ScreenshotNeo API documentation for request options. It can accept cookie or consent banners before capture and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each of those cleanup steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Every feature is available on every plan. This captures a rendered page; it does not replace testing the gallery’s responsive behavior at different widths.

Sign up free for 1,000 screenshots a month, with no card required.

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

Frequently Asked Questions

Should I use CSS Grid or Flexbox for a responsive image gallery?

This guide uses Grid because its column tracks can fill available space and wrap into additional rows. Flexbox can also wrap items, but choose the layout method based on whether you need explicit two-dimensional rows and columns.

Can I make the gallery responsive with CSS alone?

CSS can make the layout and image frames responsive. To offer the browser different image resolutions or alternate compositions, you also need responsive image markup such as srcset and sizes, or picture.

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.