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

Use max-width: 100% and height: auto on the image. The image will shrink to fit its containing block while preserving its intrinsic proportions, and it will not be enlarged beyond its natural width.

The basic responsive-image rule

Add this rule to your stylesheet:

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

max-width: 100% prevents the image from becoming wider than its containing block. If the source image is wider than the available space, the browser scales it down. If it is already smaller, the browser leaves it at its intrinsic width. height: auto recalculates the height from the source image’s intrinsic aspect ratio, preventing stretching or squashing.

This is the best default when your requirement is “fit the image on small screens, but do not make a small image blurry by enlarging it.” It also works for images placed in articles, cards, sidebars and flexible grid columns.

Make the rule reliable in real layouts

Include the image in a constrained container

The percentage in max-width: 100% is resolved against the image’s containing block. A page wrapper keeps that block from becoming unnecessarily wide:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.content {
  max-width: 70rem;
  margin-inline: auto;
  padding-inline: 1rem;
}

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

display: block removes the small inline baseline gap that can appear below an image. It is not required for responsiveness, but is useful when the image should sit flush inside a card or figure.

Prevent long URLs or other content from widening the page

An image can be responsive while its parent still overflows because of another child, such as an unbroken URL or a preformatted code sample. Inspect the element that actually exceeds the viewport; do not hide overflow on the entire page as a first fix. Constrain that content separately and keep the image rule in place.

max-width: 100% versus width: 100%

These declarations solve different design requirements:

Declaration Behavior Use it when
max-width: 100%; height: auto; Scales down an oversized image, preserves its ratio, and does not enlarge a smaller source. You want overflow prevention and natural sizing.
width: 100%; height: auto; Makes the image exactly as wide as its parent, including when that enlarges the source. The design calls for a full-bleed or always-full-width image.
Neither declaration The image normally renders at its intrinsic dimensions and may overflow a narrow container. Only when the image is guaranteed to fit, such as a deliberately fixed-size icon.

For a full-width banner inside a column, use:

.banner {
  width: 100%;
  height: auto;
  display: block;
}

Enlarging a raster image can make it look soft. If visual quality matters, combine full-width CSS with appropriately sized source files using srcset, described below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
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

Responsive images with alternate files

CSS changes the rendered size; it does not choose a smaller download for a phone or a larger one for a high-density display. Use HTML’s srcset and sizes when you have multiple versions of an image:

<img
  src="photo-800.jpg"
  srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
  sizes="(max-width: 600px) 100vw, 800px"
  width="1600"
  height="900"
  alt="Description of the photograph"
>

How the attributes work

  • srcset advertises candidate files and their intrinsic widths. The browser chooses a suitable candidate based on the rendered size and device conditions.
  • sizes tells the browser how wide the image is intended to be at each layout condition. The value must describe the CSS layout, not merely the file name.
  • src remains a fallback for browsers that do not use the candidate list.
  • width and height communicate the source aspect ratio. Browsers can reserve the correct amount of space before the file finishes loading, reducing layout movement.
  • alt supplies an accessible text alternative; responsiveness does not replace the need for meaningful alternative text.

Keep the CSS rule even when using srcset: source selection and layout sizing are complementary, not interchangeable.

Images in fixed-ratio cards and thumbnails

Some designs require every card to have the same image frame even when source photos have different proportions. Give the frame an aspect ratio, then choose whether the image may be cropped:

.image-frame {
  aspect-ratio: 16 / 9;
  overflow: hidden;
}

.image-frame img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
  display: block;
}

Choose cover when the frame matters most

object-fit: cover fills the entire frame. If the image and frame have different aspect ratios, some edges are cropped. Use object-position to keep the important subject in view, for example object-position: top for a portrait.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Choose contain when every pixel must remain visible

.image-frame img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #eee;
}

contain preserves the complete image and may leave empty bands inside the frame. This is usually preferable for product diagrams, logos and screenshots where cropping would remove information.

Do not force a frame unnecessarily

If the image should simply retain its own ratio, omit the fixed height and object-fit declarations. Set the width behavior and let height: auto calculate the result.

Responsive background images are a different case

The max-width technique applies to an <img> element. A CSS background has no intrinsic layout box, so use background sizing rules instead:

.hero {
  min-height: 20rem;
  background-image: url("hero.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

Background images are decorative in the accessibility tree. Use an actual <img> when the image conveys information, needs alternative text, participates in responsive source selection, or should reserve intrinsic space.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Common failure modes and fixes

The image still overflows on mobile

  • Check that the rule targets the actual image, not only a different class or an image inside a shadow DOM.
  • Inspect computed styles for a later width or min-width declaration overriding the intended behavior.
  • Check whether the image is inside a flex or grid item with an oversized minimum size. In those layouts, try min-width: 0 on the flex or grid child that contains the image.
  • Look for an inline style="width: ..." or a fixed pixel width on a parent.
  • Check SVG content and replaced elements that contain their own oversized internal dimensions; CSS can limit the outer element, but the SVG’s viewBox must also be sensible.

The image is stretched or squashed

Remove one-sided fixed dimensions such as width: 100%; height: 300px unless you also intend to use object-fit. For a naturally proportional image, use height: auto. For a fixed frame, set both dimensions and choose cover or contain.

There is a gap below the image

Inline images align to the text baseline. Set display: block, or adjust the parent’s line-height when the image must remain inline with text.

The image is blurry

Check whether width: 100% is enlarging a low-resolution source. Provide larger candidates through srcset, and avoid displaying a raster image substantially beyond its native dimensions.

The layout jumps while the image loads

Add accurate intrinsic width and height attributes, or reserve space with a known aspect-ratio. Do not guess dimensions: the ratio must match the actual file.

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

The focal point is cut off in a card

That is expected with object-fit: cover. Change object-position, alter the frame ratio, or use contain if cropping is unacceptable.

Testing checklist

  1. Open the page at a viewport narrower than the image’s intrinsic width.
  2. Confirm the image’s rendered width never exceeds its containing block.
  3. Resize the viewport continuously and watch for distortion, horizontal scrolling or abrupt jumps.
  4. Test the widest desktop layout to see whether width: 100% enlarges the image unexpectedly.
  5. Use browser developer tools to inspect computed width, height, max-width, min-width and object-fit.
  6. Test slow loading or disabled images: the reserved space and alternative text should still make sense.
  7. Check the narrowest card and grid column, not only the page body. A responsive rule can work in one container and fail in another because their available widths differ.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and accessibility considerations

  • Use srcset and an accurate sizes value to avoid downloading a desktop-sized file for a small mobile slot.
  • Provide intrinsic dimensions so the browser can allocate layout space before decoding.
  • Write concise, useful alt text for informative images. Use an empty alt="" only for genuinely decorative images.
  • Do not use CSS cropping to hide essential information. If every part must remain readable, use contain or a naturally sized image.
  • Lazy loading can defer below-the-fold downloads, but it does not replace responsive sizing or correct dimensions. Choose loading behavior according to the image’s position and importance.

Or skip the browser setup

If you need rendered screenshots of a responsive page rather than CSS embedded in your application, ScreenshotNeo returns a PNG, JPEG, WebP or PDF from one request. It accepts the page’s cookie or consent banner before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

The API supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, click-before-capture actions, hidden selectors, selector/delay/network-idle waits, request and resource blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed 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.

cURL

See the complete option reference in the ScreenshotNeo documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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}`);

ScreenshotNeo includes an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Quick decision guide

Your requirement Recommended implementation
Stop overflow and preserve natural size max-width: 100%; height: auto;
Always fill the parent width width: 100%; height: auto;
Uniform card frame, cropping acceptable Frame aspect-ratio plus object-fit: cover
Uniform frame, all content required Frame aspect-ratio plus object-fit: contain
Different downloads for different screens srcset and sizes, alongside CSS sizing

Frequently Asked Questions

Does responsive CSS require a media query?

No. The percentage-based sizing rules respond continuously to the containing block, so a media query is only needed when the design changes at a breakpoint.

Can I make an image responsive with only HTML?

HTML can offer responsive files with srcset and sizes, but CSS is still needed to control how the selected image fits its layout box.

Should I use height: auto on SVGs?

Usually yes when preserving the SVG’s intrinsic ratio, but verify that the SVG has a valid viewBox and does not contain an internal fixed dimension that defeats the intended layout.

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.