Responsive Images
Keeping images from overflowing their containers, and serving the right image size for the screen.
2 min read
Images are the most common thing to break a responsive layout — a large fixed-size image can force a horizontal scrollbar on a narrow screen if it isn't handled deliberately.
The one rule almost every project needs
img {
max-width: 100%;
height: auto;
display: block;
}max-width: 100% prevents an image from ever exceeding the width of its container, while still allowing it to display at its natural size if it's already smaller. height: auto keeps the aspect ratio intact as the width scales — without it, a fixed height combined with a flexible width would stretch or squash the image. This one rule belongs in nearly every stylesheet's base styles.
display: block removes the small gap that appears below inline images (images are inline by default, which leaves room for descenders like a lowercase "g" in surrounding text) — a subtle but frequent source of "why is there mystery whitespace under my image."
Reserving space to avoid layout shift
img {
aspect-ratio: 16 / 9;
width: 100%;
object-fit: cover;
}If an image's dimensions aren't known until it finishes loading, the page can visibly jump as it loads — content above and below shifts once the image's real size is known. Setting aspect-ratio reserves the correct space immediately, before the image loads, eliminating that shift. object-fit: cover then crops the image to fill that box without distorting it, similar to a CSS background-size: cover.
object-fit in more detail
.avatar {
width: 48px;
height: 48px;
border-radius: 50%;
object-fit: cover;
}
.logo {
width: 200px;
height: 60px;
object-fit: contain;
}object-fit: cover scales an image to fill its box, cropping any overflow — good for photos where cropping edges is acceptable, like an avatar. object-fit: contain scales it to fit entirely within the box without cropping, leaving empty space if the aspect ratios don't match — better for a logo where nothing should ever be cut off.
Serving different image sizes (HTML, not CSS)
<img
src="/photo-800.jpg"
srcset="/photo-400.jpg 400w, /photo-800.jpg 800w, /photo-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="A mountain landscape at sunset"
/>CSS controls how an image displays, but srcset/sizes (HTML attributes) control which file the browser downloads in the first place — letting a phone download a 400px image instead of wastefully downloading the same 1200px file a desktop needs. This is worth knowing even in a CSS course, because "responsive images" as a full topic spans both layers: HTML decides what to download, CSS decides how it's displayed once it arrives.