Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
CSS

Image Grid View in HTML and CSS: Responsive, Accessible Galleries

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

Use a semantic collection of <img> elements inside a CSS Grid container. Let Grid control columns and gaps, then decide whether each tile should crop with object-fit: cover or show the complete source with object-fit: contain. Add intrinsic dimensions, useful alternative text, responsive image sources, and a reflowing track definition so the gallery remains usable on narrow screens and at high zoom.

Start with semantic HTML

When an image conveys content, keep it as an HTML image rather than using a CSS background. A list is a useful semantic wrapper for a gallery because every item is a distinct piece of content. The example below includes concise alternative text and dimensions that reserve space before each file finishes loading.

<ul class="gallery">
  <li class="gallery__item">
    <img
      src="images/mountain-640.jpg"
      alt="Snow-covered mountain above a blue lake"
      width="640"
      height="427"
      loading="lazy"
    >
  </li>
  <li class="gallery__item">
    <img
      src="images/market-640.jpg"
      alt="Outdoor market stalls under striped awnings"
      width="640"
      height="427"
      loading="lazy"
    >
  </li>
  <li class="gallery__item">
    <img
      src="images/forest-640.jpg"
      alt="Sunlight through a dense green forest"
      width="640"
      height="427"
      loading="lazy"
    >
  </li>
</ul>

Write alt text that communicates the image’s purpose, not a filename. If an image is purely decorative and conveys no information, use the alternative-text treatment appropriate to that context (often an empty alt="") instead of inventing a description. The width and height attributes should reflect the source’s intrinsic dimensions or its intended aspect ratio; they let the browser reserve layout space and reduce movement while files load.

Build a responsive grid with CSS Grid

Grid defines the gallery’s columns while each image fills its own item. This fluid track definition allows columns to reflow as available width changes rather than forcing a fixed desktop arrangement onto a phone or zoomed page.

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
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 1rem;
  list-style: none;
  margin: 0;
  padding: 0;
}

.gallery__item {
  min-width: 0;
  overflow: hidden;
  background: #eee;
}

.gallery__item img {
  display: block;
  width: 100%;
  height: 100%;
}

minmax(220px, 1fr) is an example, not a universal breakpoint or required column count. Increase or decrease the minimum to suit the content and test the result at the narrowest supported width, normal desktop widths, and high zoom. If every card needs a predictable shape, give the item (or image) an aspect ratio:

.gallery__item {
  aspect-ratio: 4 / 3;
}

.gallery__item img {
  aspect-ratio: 4 / 3;
  object-fit: cover;
}

The grid can also use explicit media-query tracks when a design calls for known changes at chosen widths. The important requirement is reflow: columns must become fewer or narrower instead of overflowing the viewport.

Choose between cover and contain

object-fit controls how an image with a constrained box is rendered. The choice is a content decision, not merely a visual preference.

Value What it does Use it when Trade-off
cover Scales the image until the box is filled while preserving its aspect ratio. Uniform tiles and a tidy wall of cards matter more than showing every edge. Parts of the source can be cropped, including an important subject near an edge.
contain Scales the complete image so it fits inside the box while preserving its aspect ratio. The whole image must remain visible, such as artwork, diagrams, or product documentation. Unused space can appear as bands around the image.
/* Consistent thumbnails; inspect focal points for unwanted crops. */
.gallery__item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Complete images; choose a background that makes bands intentional. */
.gallery--complete .gallery__item {
  display: grid;
  place-items: center;
  background: #f2f2f2;
}

.gallery--complete .gallery__item img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

If a face, logo, or product detail is being cut off by cover, change to contain, alter the tile’s aspect ratio, or adjust the image’s focal position with object-position. Do not force both dimensions without an appropriate fit strategy: that can stretch the source.

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

Serve an appropriate image resource

A grid may display the same logical image at many rendered sizes. Responsive image markup lets the browser select among resources instead of downloading one oversized file for every tile. With width descriptors, pair srcset with sizes that describe the slot’s likely CSS width.

<img
  src="images/mountain-640.jpg"
  srcset="
    images/mountain-320.jpg 320w,
    images/mountain-640.jpg 640w,
    images/mountain-1280.jpg 1280w
  "
  sizes="(min-width: 900px) 25vw, (min-width: 600px) 33vw, 100vw"
  alt="Snow-covered mountain above a blue lake"
  width="1280"
  height="853"
  loading="lazy"
>

The values in sizes should match your actual layout, including the gap and any page padding; the sample is only a starting point. Generate source files that cover the rendered slot rather than relying on a single enormous original.

Use <picture> when the source itself should change, such as an art-directed crop or a format choice that your delivery setup supports:

<picture>
  <source media="(min-width: 800px)" srcset="images/hero-wide.jpg">
  <source media="(max-width: 799px)" srcset="images/hero-tall.jpg">
  <img
    src="images/hero-tall.jpg"
    alt="A cyclist crossing a bridge at sunrise"
    width="800"
    height="1000"
  >
</picture>

Keep the fallback <img> complete and accessible. The same principles apply whether the image is in a card, a list item, or a detail view.

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

Prevent layout shift and unnecessary work

  • Reserve geometry: provide accurate width and height attributes, or an equivalent aspect-ratio rule, so the grid does not jump when files arrive.
  • Defer below-the-fold files: add loading="lazy" to images that are initially off screen. Do not blindly lazy-load the first visible images; they are needed for the initial view.
  • Fit the available width: use max-width: 100% when an image is not controlled by a full-width tile, and keep the height relationship proportional.
  • Keep tile content bounded: min-width: 0 on grid children prevents long content from forcing a track wider than the viewport.
  • Check zoom and orientation: reflow should still work when text is enlarged or a device changes orientation. A fixed column count that works only at one width is fragile.
.content-image {
  display: block;
  max-width: 100%;
  height: auto;
}

The W3C WAI techniques for fitting images and reflowing columns describe these as advisory implementation techniques. Validate the actual page at the widths and zoom levels your audience uses rather than assuming one breakpoint solves every layout.

Use captions and links without breaking the grid

If an image needs a visible explanation, put the image and caption in the same grid item. A caption can remain readable while the image keeps its chosen fit mode.

<li class="gallery__item">
  <figure>
    <img
      src="images/bridge-640.jpg"
      alt="Stone bridge over a narrow river"
      width="640"
      height="427"
      loading="lazy"
    >
    <figcaption>Old stone bridge</figcaption>
  </figure>
</li>
.gallery__item figure {
  margin: 0;
}

.gallery__item figcaption {
  padding: .5rem .75rem;
  font-size: .9rem;
}

When the thumbnail is a link, make the link target and focus state obvious. Do not remove meaningful alternative text simply because a caption is visible; the alternative should still identify the image’s purpose for someone who cannot see it.

Troubleshoot common grid problems

Images are stretched

This happens when a fixed width and height change the source ratio without a fit rule. Set object-fit: cover or contain, or let the height remain automatic with height: auto when the tile does not need a fixed shape.

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

Important content is cut off

cover deliberately crops. Switch that tile to contain, use a less aggressive aspect ratio, or reposition the focal point. If the entire source is legally or technically required, do not use a crop as the only view.

Blank bands appear

That is the expected result of contain when the source ratio differs from the box. Choose a deliberate background, remove the fixed box, or accept the bands when complete-image visibility is the priority.

The page jumps while images load

Add accurate dimensions to every content image and make sure the CSS box does not contradict those proportions. Missing geometry leaves the browser guessing until each response arrives.

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

The gallery overflows on a phone

Look for a fixed number of columns, a grid child with an unbreakable width, or an image missing max-width: 100%. Use fluid tracks, min-width: 0, and test at narrow widths and zoom.

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

All images download immediately

Confirm that below-the-fold items have loading="lazy" and that the browser can reach the image URLs. Lazy loading is a hint, not a guarantee that every request will be postponed; keep critical above-the-fold images available.

The wrong responsive source is selected

Check that each srcset width descriptor is accurate and that sizes describes the real slot. An incorrect sizes value can make the browser choose an unnecessarily large or small resource.

A complete minimal example

This page combines semantic markup, fluid columns, reserved geometry, lazy loading, and complete-image visibility. Change one class to compare the two fit policies.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Responsive image grid</title>
  <style>
    .gallery {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 1rem;
      list-style: none;
      margin: 0;
      padding: 1rem;
    }
    .gallery__item {
      aspect-ratio: 4 / 3;
      min-width: 0;
      overflow: hidden;
      background: #eee;
    }
    .gallery__item img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>
<body>
  <ul class="gallery">
    <li class="gallery__item">
      <img src="images/mountain-640.jpg" alt="Snow-covered mountain above a blue lake" width="640" height="427" loading="lazy">
    </li>
    <li class="gallery__item">
      <img src="images/market-640.jpg" alt="Outdoor market stalls under striped awnings" width="640" height="427" loading="lazy">
    </li>
    <li class="gallery__item">
      <img src="images/forest-640.jpg" alt="Sunlight through a dense green forest" width="640" height="427" loading="lazy">
    </li>
  </ul>
</body>
</html>
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 you need rendered screenshots of pages or grids for documentation, previews, or automated checks, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. It accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server gives Claude, Cursor, and other MCP clients take_screenshot, get_page_info, and capture_pdf tools.

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

Here is a complete cURL request; replace the URL with your page:

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

Python:

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)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the parameter reference and the other 63 options in the ScreenshotNeo documentation. They include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, user agent, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work.

Plan Allowance and price
Free 1,000 shots per month, no card
Starter $5 for 3,000 shots
Growth $15 for 15,000 shots
Pro $39 for 60,000 shots
Scale $99 for 250,000 shots
Business $249 for 1,000,000 shots

Yearly billing gives two months free, and every feature is available on every plan. Start with 1,000 free screenshots a month with no card, then choose a paid plan from $5 for 3,000 if your capture volume requires it.

FAQ

Should a gallery always use square thumbnails?

No. Choose an aspect ratio that supports the subject and the surrounding design. A square is only one possible tile shape; forcing it can crop or shrink content unnecessarily.

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.

Can one gallery mix cover and contain?

Yes. Apply the fit policy per item when some assets are promotional crops and others must remain fully visible. Make the difference intentional and understandable to users.

Is CSS Grid required for every image collection?

No. Grid is a strong choice for two-dimensional rows and columns, but the correct layout depends on the surrounding interface. This pattern is aimed at a responsive gallery where column reflow and consistent gaps matter.

Frequently Asked Questions

Should a gallery always use square thumbnails?

No. Choose an aspect ratio that supports the subject and the surrounding design. A square is only one possible tile shape; forcing it can crop or shrink content unnecessarily.

Can one gallery mix cover and contain?

Yes. Apply the fit policy per item when some assets are promotional crops and others must remain fully visible. Make the difference intentional and understandable to users.

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

Is CSS Grid required for every image collection?

No. Grid is a strong choice for two-dimensional rows and columns, but the correct layout depends on the surrounding interface. This pattern is aimed at a responsive gallery where column reflow and consistent gaps matter.

Quick Recap

SaleBestseller No. 1
HTML and CSS: Design and Build Websites
HTML and CSS: Design and Build Websites
HTML CSS Design and Build Web Sites; Comes with secure packaging; It can be a gift option
$14.18
SaleBestseller No. 3
SaleBestseller No. 4
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.