ScreenshotNeo

BlogHow-to

How to Set the Maximum Width of an Image in CSS

Use max-width: 100% with height: auto to keep images inside their containers without distortion or unwanted upscaling.

By the ScreenshotNeo team1 October 20266 min read

max-width: 100% limits an image to the width of its containing block. Add height: auto so the browser preserves the image’s aspect ratio:

img {
  max-width: 100%;
  height: auto;
}

This lets an image shrink when it is wider than its container, while a smaller intrinsic image remains smaller. That differs from width: 100%, which makes the image occupy the available width and can enlarge a low-resolution source.

Why max-width: 100% works

The percentage is measured against the image’s containing block. If the container is 640px wide and the source image is 1,200px wide, the rendered image can shrink to 640px. If the source is 320px wide, max-width does not force it to 640px.

Use a broad selector only when every image on the site should follow this rule. For a blog or article area, scope it to the component:

.article-content img {
  max-width: 100%;
  height: auto;
}

See the MDN max-width reference for the sizing behavior and constraints.

Complete responsive image example

<article class='article-content'>
  <h1>A responsive article image</h1>
  <img
    src='/images/diagram-1200.jpg'
    width='1200'
    height='800'
    alt='A diagram showing the request flow'
  >
</article>
.article-content {
  max-width: 42rem;
  margin-inline: auto;
  padding-inline: 1rem;
}

.article-content img {
  display: block;
  max-width: 100%;
  height: auto;
}

display: block removes the small inline baseline gap that can appear below images. The width and height attributes describe the intrinsic dimensions, allowing the browser to reserve the correct aspect ratio before the file finishes loading.

max-width versus width

Declaration What it does Use it when
max-width: 100% Caps the rendered width at the container width; does not enlarge smaller images. You want images to fit without forced upscaling.
width: 100% Makes the image fill the available width, including by enlarging a smaller source. The design requires every image to span the container.
height: auto Calculates height from the rendered width and intrinsic aspect ratio. You want proportional scaling.

For most article content, use max-width: 100%; height: auto. Use width: 100% only when filling the box is intentional.

Prevent layout shift with intrinsic dimensions

Include accurate width and height attributes when you know the source dimensions:

<img
  src='/images/photo.jpg'
  width='1600'
  height='900'
  alt='Mountain landscape'
>

CSS can still make that image responsive. The attributes give the browser an aspect ratio early, so surrounding content is less likely to jump while the image loads. The MDN img reference covers these attributes.

When the image must fill a fixed box

max-width controls the element’s size; it does not crop the image. For a card with fixed dimensions, use object-fit:

.thumbnail {
  width: 320px;
  height: 180px;
  object-fit: cover;
  object-position: center;
}

Use cover when cropping is acceptable, or contain when the whole image must remain visible:

.thumbnail--uncropped {
  object-fit: contain;
  background: #f3f4f6;
}

Do not add a fixed height to a normally responsive content image unless you also choose the intended crop behavior.

Responsive source selection with srcset and sizes

A CSS width limit changes the displayed size. It does not automatically make the browser download a smaller file. Use responsive image markup when bandwidth matters:

<img
  src='/images/hero-800.jpg'
  srcset='/images/hero-400.jpg 400w,
          /images/hero-800.jpg 800w,
          /images/hero-1600.jpg 1600w'
  sizes='(max-width: 42rem) 100vw, 42rem'
  width='1600'
  height='900'
  alt='Product dashboard on a laptop'
>
.hero img {
  max-width: 100%;
  height: auto;
}

srcset supplies candidate files and sizes tells the browser the intended layout width. This is separate from the CSS containment rule. Read MDN’s responsive images guide for the selection algorithm.

Images inside flex and grid layouts

Flex and grid items can have a default minimum size that prevents shrinking. If an image still overflows, constrain the item as well:

.media-layout {
  display: flex;
  gap: 1rem;
}

.media-layout__content {
  min-width: 0;
}

.media-layout img {
  max-width: 100%;
  height: auto;
}

For grid, minmax(0, 1fr) allows a track to shrink:

.article-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 18rem;
  gap: 2rem;
}

Common problems and fixes

Symptom Likely cause Fix
The image still overflows A min-width rule, a wider containing block, or a more specific selector wins. Inspect computed styles, remove or override min-width, and verify the actual containing block. MDN notes that min-width can override max-width.
The image is blurry width: 100% or another rule enlarges a small source. Use max-width: 100%, provide a larger source, or add srcset.
The image is distorted A fixed CSS height conflicts with the aspect ratio. Use height: auto, or deliberately set object-fit for a fixed box.
Content jumps during loading No intrinsic dimensions or reserved aspect ratio. Add accurate width and height attributes.
The image fits but the crop is wrong Width constraints do not define cropping. Set the box dimensions and choose object-fit: cover or contain.
Mobile bandwidth is high The browser downloads an oversized source even though CSS displays it smaller. Use srcset and sizes with appropriately sized files.

Testing checklist

  1. Resize the viewport below the image’s intrinsic width.
  2. Confirm the image never exceeds its content box.
  3. Check that a smaller source is not being stretched unintentionally.
  4. Compare the rendered aspect ratio with the source aspect ratio.
  5. Inspect computed styles for conflicting width, height, min-width, or selector specificity.
  6. Use the network panel to verify that srcset selects an appropriate file.

Or skip the browser setup

If you need screenshots of pages containing responsive images, ScreenshotNeo captures the rendered page through one API request. Its capture options include full-page shots with lazy images loaded, custom viewports and device presets, retina scale, custom CSS and JavaScript, and waiting for a selector, delay, or network idle.

cURL (see the ScreenshotNeo API documentation):

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

Cookie banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages and failed loads are never billed, and response headers report the page verdict and whether the shot was billed. An MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Performance, reliability and cost notes

  • Prefer appropriately sized sources with srcset to reduce transfer and decoding work.
  • Keep intrinsic dimensions accurate so layout can be reserved before decoding.
  • Use loading='lazy' for below-the-fold content when it suits the page; do not lazy-load the primary image if it delays the main content.
  • For automated screenshots, wait for the image or a stable layout condition before capture. ScreenshotNeo supports selector, delay and network-idle waits.
  • If you capture the same URL repeatedly, ScreenshotNeo supports caching with a TTL you choose. Clean shots are billed; cache hits, failed loads, timeouts, blank pages and bot checks are not billed.

FAQ

Does max-width: 100% enlarge a small image?

No. It sets an upper limit. A smaller intrinsic image keeps its rendered size unless another rule enlarges it.

Should I use width: 100% instead?

Use it when the design requires the image to fill the container. Use max-width: 100% when avoiding unwanted upscaling matters.

Why do I also need height: auto?

It lets the browser calculate height from the constrained width and preserves the source proportions.

Will this reduce image downloads?

No. Add srcset and sizes when the browser should choose a smaller source file.

Can this CSS crop an image?

No. Use a fixed box with object-fit when cropping or containment is part of the design.