An image dropped into a page with no responsive handling will happily overflow its container at its full native size, breaking the layout on smaller screens. CSS and HTML together give you a few layers of control over how images behave as the viewport changes — from a one-line baseline fix to a full browser-driven image-switching system.
The Baseline Fix
img {
max-width: 100%;
height: auto;
}
This single rule should be close to a global default on every site. max-width: 100% stops an image from ever exceeding the width of its container, and height: auto keeps its aspect ratio intact as the width shrinks — without this second line, a width-only fix would squash the image vertically.
Controlling the Fit with object-fit
When an image needs to fill a box with a fixed aspect ratio — a square thumbnail, a wide banner — object-fit controls how it behaves inside that box instead of stretching or distorting it.
.thumbnail {
width: 200px;
height: 200px;
object-fit: cover;
}
With object-fit: cover, the image scales up to completely fill the 200×200 box, cropping any excess rather than squishing the image out of proportion. object-fit: contain is the alternative — it shrinks the image to fit entirely inside the box instead, which can leave empty space around it but never crops anything.
Serving Different Image Sizes with srcset
The CSS techniques above resize the same image file to fit its container — but a phone still downloads the same huge image a 4K monitor would get, wasting bandwidth. The HTML-level srcset attribute lets the browser choose from several actual image files based on the device's screen:
<img
src="photo-800w.jpg"
srcset="photo-400w.jpg 400w, photo-800w.jpg 800w, photo-1600w.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="A mountain landscape at sunset"
/>
srcset lists the available image files along with their actual pixel widths, and sizes tells the browser how wide the image will actually be displayed at different viewport widths — here, full width on screens 600px or narrower, and half width otherwise. The browser combines this information with the device's screen density to download only the smallest file that will still look sharp, instead of always fetching the largest version.
Putting It Together
In practice, most sites layer all three: max-width: 100%; height: auto; as a safety net everywhere, object-fit for images placed inside fixed-size boxes (like card layouts or thumbnail grids), and srcset/sizes on larger hero or content images where bandwidth savings actually matter.
