Sub topic 10
Making images flexible
This chapter assumes you know basic HTML, CSS selectors and the box model, and the units px, em, rem, and %. It also assumes you have read the chapters on the viewport meta tag, min-width media queries, and fluid units. Here you will make images fit any container, avoid layout jumps while they load, and serve different files to different screens.
Why images break responsive layouts
An <img> element is a replaced element. Its default size comes from the file's intrinsic dimensions, not from the CSS box around it. A 1600px-wide photo in a 360px-wide column overflows the column and causes horizontal scrolling. Fluid text and flexible grids can't fix this, because the image ignores the container's width.
Flexible images need to solve three problems:
- Fit: the image must never be wider than its container.
- Stability: the browser should reserve the right amount of space before the file arrives.
- Efficiency: a phone should not download a file sized for a 4K monitor.
The core rule: max-width and height
The base rule is short:
img {
max-width: 100%;
height: auto;
}max-width: 100% caps the image at the width of its containing block. height: auto recalculates the height from the intrinsic aspect ratio, so the image scales without distortion.
Two details matter here:
max-widthonly shrinks. A 300px image in a 900px container stays 300px wide. That is usually what you want, because enlarging a raster image makes it blurry. If you want it to fill the container, usewidth: 100%instead.- Without
height: auto, an image with aheight="400"attribute keeps a fixed height while its width shrinks. The result is a squashed picture.
Images are inline by default, so they sit on the text baseline and leave a small gap below. Add display: block for standalone images, such as in cards, to remove the gap.
img {
display: block;
max-width: 100%;
height: auto;
}Reserving space with width and height attributes
Always put width and height attributes on the <img> tag, with the file's intrinsic pixel values:
<img src="harbor-800.jpg" alt="Fishing boats in a harbor at dawn" width="800" height="450">Modern browsers use these two numbers to compute an aspect ratio (16 / 9 here) before the file loads. Combined with height: auto in your CSS, the browser reserves a box of the right shape. The text below doesn't jump when the image arrives. That jump is called layout shift, and it is part of what the Cumulative Layout Shift metric measures.
The attributes set the ratio, not the final size. CSS still controls the rendered size.
For boxes that aren't <img> elements, or when you want a fixed shape regardless of the file, use aspect-ratio:
.thumb {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}object-fit: cover scales the image to fill the box and crops the overflow. Use contain to show the whole image with empty space around it. object-position chooses which part survives the crop, for example object-position: center top to keep faces in portrait photos.
Images inside flex and grid items
A common surprise: an image inside a flex or grid item can force the item wider than its track. Flex and grid items have min-width: auto, which means they refuse to shrink below their content's minimum size. A large image sets that minimum.
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
gap: 1rem;
}
.gallery > * {
min-width: 0;
}
.gallery img {
display: block;
width: 100%;
height: auto;
}The min-width: 0 rule lets items shrink. The min(100%, 15rem) inside minmax() stops the minimum track size from exceeding the container on very narrow screens.
Resolution switching with srcset and sizes
Scaling with CSS doesn't change the file size. A phone still downloads the large file. To fix that, give the browser several versions and let it choose.
<img
src="harbor-800.jpg"
srcset="harbor-400.jpg 400w,
harbor-800.jpg 800w,
harbor-1600.jpg 1600w"
sizes="(min-width: 64em) 33vw,
(min-width: 40em) 50vw,
100vw"
alt="Fishing boats in a harbor at dawn"
width="800"
height="450">Here is how the browser reads this:
srcsetlists candidate files withwdescriptors, which are each file's intrinsic width in pixels.sizestells the browser how wide the image will be displayed, before layout and CSS are finished. It is a list of media conditions with lengths, and the first matching condition wins. The last entry has no condition and acts as the default.- The browser multiplies the displayed width by the device pixel ratio, then picks the smallest candidate that covers it. A 400px slot on a 2x screen needs about 800 pixels, so it picks
harbor-800.jpg.
The sizes conditions are media queries, but they describe layout only. They should mirror your CSS breakpoints. If the CSS and sizes disagree, the browser picks a file that is too large or too small.
Keep src as a fallback for browsers that ignore srcset. The browser may also pick a different candidate based on network conditions or cache contents, and the HTML spec lets it do so.
Art direction with picture
srcset gives the same image at different sizes. Sometimes a smaller screen needs a different crop. A wide landscape shrunk to phone width makes the subject tiny. The <picture> element handles this:
<picture>
<source media="(min-width: 50em)" srcset="harbor-wide.jpg">
<source media="(min-width: 30em)" srcset="harbor-square.jpg">
<img src="harbor-tall.jpg" alt="Fishing boats in a harbor at dawn" width="600" height="800">
</picture>The browser walks the <source> elements in order and uses the first whose media attribute matches. Unlike sizes, these media conditions are binding, not hints. The <img> is required. It is the fallback and also the element that carries alt, width, height, and your CSS.
<picture> also selects by file format with the type attribute, for example offering image/avif before image/jpeg. You can combine format and art direction, but each extra source adds maintenance work. Use <picture> only when the crop actually changes.
Background images
CSS background images don't support srcset. Swap them with media queries, mobile-first:
.hero {
background-image: url("hero-small.jpg");
background-size: cover;
background-position: center;
min-height: 12rem;
}
@media (min-width: 40em) {
.hero {
background-image: url("hero-large.jpg");
min-height: 20rem;
}
}Use backgrounds only for decoration. They have no alt text, so content images belong in <img>.
Choosing a technique
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `height` fixed in CSS with `max-width: 100%` | Image is squashed when the container is narrow | Use `height: auto` |
| No `width` and `height` attributes | Content jumps as images load | Add the intrinsic dimensions |
| `sizes` omitted with `w` descriptors | Browser assumes `100vw` and downloads too much | Write `sizes` to match your layout |
| Image stretches a flex or grid item | Horizontal scrollbar | Set `min-width: 0` on the item |
| Only one very large file | Slow loads on mobile | Provide several widths in `srcset` |
Testing
Resize the browser window and watch for horizontal scrollbars. In the developer tools Network panel, reload at different widths and check which file the browser requested. Note that the browser may reuse a larger cached file after you shrink the window, so disable the cache or use a hard reload when testing srcset. The currentSrc property of the <img> element in the console shows which candidate is in use.
Exercise
A card contains <img src="photo.jpg" width="1200" height="800" alt="Lake">. The page CSS sets img { max-width: 100%; } and nothing else. On a 360px-wide screen the photo fits the card but looks stretched vertically. What causes this, and what single declaration fixes it?
Show answer
The height="800" attribute still applies as a presentational height, while max-width shrinks only the width, so the image keeps its 800px height and distorts. Adding height: auto; to the img rule makes the browser compute the height from the aspect ratio and removes the distortion.
Exercise
Your layout shows an image at 100vw below 40em, 50vw from 40em, and 33vw from 64em. Write the sizes attribute for it.
Show answer
sizes="(min-width: 64em) 33vw, (min-width: 40em) 50vw, 100vw". The conditions run from largest to smallest because the first match wins, and the final entry without a condition is the default.