Sub topic 11
Serving the right image size
This chapter assumes you can write semantic HTML, know CSS units and the box model, and can use the browser's developer tools. It builds on the single-column fluid layout from earlier chapters. In that layout, an image fills the width of its column, and the column width changes with the screen.
Images are usually the heaviest part of a page. A phone on a mobile connection should not download a 1600-pixel photo to show it in a 360-pixel column. This chapter covers how to let the browser choose the right file, how to avoid layout shift, and when to defer loading.
The working model
A browser decides which image file to download before it has finished laying out the page. To choose well, it needs two facts:
- What files exist, and how wide each one is. You supply this with
srcset. - How wide the image will be on screen. You supply this with
sizes.
The browser also knows the device pixel ratio (DPR). A screen with DPR 2 packs four physical pixels into each CSS pixel, so a 360 CSS-pixel slot needs about 720 pixels of image data to look sharp.
The browser multiplies the slot width by the DPR and picks the smallest file that covers the result. You give it the options, and it makes the choice. This is why the technique suits mobile-first design: you describe the layout once, and each device picks what fits.
A complete example
This markup serves one photo in three widths:
<img
src="team-800.jpg"
srcset="team-400.jpg 400w, team-800.jpg 800w, team-1600.jpg 1600w"
sizes="(min-width: 64em) 50vw, 100vw"
width="800"
height="450"
alt="The support team standing in front of the office"
loading="lazy">Each attribute has a separate job.
srcis the fallback. Browsers that do not understandsrcsetuse it, and it is the file used when no other candidate fits.srcsetlists candidates. Thewnumber is the file's real pixel width, not a display width. It must match the file.sizesdescribes the slot. Read it left to right: if the viewport is at least64emwide, the image takes50vw. Otherwise it takes100vw. The last entry has no condition and acts as the default.widthandheightgive the image's intrinsic dimensions, which lets the browser compute the aspect ratio before the file arrives.loading="lazy"delays the download until the image is near the viewport.altis the text alternative. It is still required, and it matters more when the image fails to load on a weak connection.
Worked calculation
Take a phone with a 390 CSS-pixel viewport and DPR 3. The sizes value resolves to 100vw, so the slot is 390 CSS pixels. The target is 390 × 3 = 1170 image pixels. The smallest candidate that is at least 1170 wide is team-1600.jpg, so the browser downloads that.
Now take a 390-pixel-wide phone with DPR 1, for example an older budget device. The target is 390 pixels, and the browser picks team-400.jpg.
The same markup gives the high-DPR phone a sharp image and the low-DPR phone a small download. Your candidate list sets what is possible, so it should include a size near the target for the most common cases.
Now a desktop at 1280 CSS pixels and DPR 1. The viewport is above 64em (1024px), so the slot is 50vw = 640 pixels. The browser picks team-800.jpg.
Writing a good sizes value
sizes is where most mistakes happen, because it must describe your CSS layout without access to it. The browser reads sizes before the stylesheet has been applied to the image, so it cannot work the width out for itself.
Keep these rules in mind:
- Mirror your layout. If the card list is one column below
40em, two columns from40em, and three from64em, the image width changes at those same points. - Account for padding and gaps.
100vwis only correct if the image touches both screen edges. With1remof padding on each side, you can writecalc(100vw - 2rem). - Use the same breakpoints as the CSS. Media conditions in
sizesuse the same syntax as media queries, and em values in them are based on the browser's default font size. - Order matters. The browser uses the first condition that matches.
For the card layout from the media-query chapter, a matching sizes might be:
<img
src="card-600.jpg"
srcset="card-300.jpg 300w, card-600.jpg 600w, card-1200.jpg 1200w"
sizes="(min-width: 64em) calc((100vw - 4rem) / 3),
(min-width: 40em) calc((100vw - 3rem) / 2),
calc(100vw - 2rem)"
width="600"
height="400"
alt="A product shown on a wooden table"
loading="lazy">The numbers are approximate on purpose. A slightly wrong sizes value still works. It just makes the browser choose a file that is a little larger or smaller than ideal. A badly wrong value, such as leaving out sizes entirely, makes the browser assume 100vw, which wastes bandwidth when the image is only a third of the screen.
Preventing layout shift
When an image has no known size, the browser reserves no space for it. The text below sits at the top of the page until the file arrives, then jumps down. This is layout shift, and it is especially annoying on mobile, where the jump can move a button out from under a finger.
Setting width and height attributes fixes this. Modern browsers use them to compute an aspect ratio, so the space is reserved before the image loads. For the image to still scale fluidly, pair the attributes with this CSS:
img {
max-inline-size: 100%;
block-size: auto;
}max-inline-size: 100% stops the image from overflowing its container. block-size: auto lets the height follow the width while keeping the ratio from the attributes. Without block-size: auto, the fixed height attribute would stretch the image once the width shrinks.
Lazy loading and its limits
loading="lazy" tells the browser to wait until an image is close to the viewport before fetching it. For long pages on mobile, this saves data on images the user may never scroll to.
Do not lazy-load everything:
- Do not lazy-load the main image that is visible when the page first opens. Delaying it makes the page appear slower. Leave
loadingoff, or useloading="eager", for these images. - Always provide
widthandheighton lazy images. Otherwise the space is not reserved, and the page shifts as the user scrolls. - Lazy loading depends on the browser's idea of "near the viewport", which you do not control exactly.
A reasonable rule is that images in the first screen load normally, and images below it load lazily.
Different crops with picture
srcset and sizes change the file size but not the content. Sometimes a small screen needs a different image, such as a tighter crop where faces are still visible. The picture element handles this, and it is called art direction.
<picture>
<source media="(min-width: 64em)" srcset="hero-wide.jpg">
<img
src="hero-tight.jpg"
width="800"
height="800"
alt="A baker holding a tray of loaves">
</picture>The browser checks each source in order and uses the first whose media condition matches. The img is the fallback and the default, which keeps the mobile-first order: the base case is the small image, and the wide image is added with min-width. The img element is required, and it carries the alt text.
You can also use picture with a type attribute to offer modern formats such as AVIF or WebP, with JPEG as the fallback. The browser skips any source whose type it does not support.
| Need | Tool | What changes |
|---|---|---|
| Same picture, smaller file | `srcset` with `w` and `sizes` | File size |
| Different crop or composition | `picture` with `media` | Image content |
| Newer file format | `picture` with `type` | Format |
| Defer offscreen images | `loading="lazy"` | When it downloads |
Common errors
- Wrong
wvalues. If the descriptor says800wbut the file is 600 pixels wide, the browser makes bad choices. Check real file dimensions. - Missing
sizes. The browser falls back to100vw. - Missing
widthandheight, which causes layout shift. - Lazy-loading the top image, which slows the first view.
- Testing only on a desktop with DPR 1. Use device emulation with a higher DPR to see different files chosen, and check the Network panel to confirm which file was downloaded.
- Forgetting that browsers may cache a larger file. If you resize the window after load, the browser may keep the bigger file it already has rather than download a smaller one. Reload to test properly.
- Serving huge originals. Resizing with CSS does not reduce the download. Produce real smaller files.
Checking your work
Open developer tools, switch on device emulation, and choose a phone profile. Open the Network panel, filter by images, and reload. The size column shows the transfer size of each file. Change the device or its pixel ratio, reload, and compare. If a phone downloads the 1600-pixel file in a 390-pixel layout at DPR 1, your sizes value is likely wrong.
Exercise
A page shows a photo at 50vw on viewports of 40em and wider, and at 100vw below that. The photo has files of 480w, 960w and 1920w. A phone with a 400 CSS-pixel viewport and DPR 2 loads the page. Write the sizes attribute, then say which file the browser picks.
Show answer
sizes="(min-width: 40em) 50vw, 100vw". A 400px viewport is below 40em (640px), so the slot is 100vw = 400 CSS pixels. At DPR 2 the target is 800 image pixels. The smallest file at least 800 wide is the 960w file, so the browser picks it.
Exercise
An image has no width or height attributes and the CSS rule img { max-inline-size: 100%; block-size: auto; }. The text below it jumps down when the image loads. What do you add, and why does it help even though the CSS makes the image fluid?
Show answer
Add width and height attributes matching the file's intrinsic size. The browser uses them to calculate the aspect ratio before the file downloads, so it reserves the right amount of space. The CSS then lets the image scale fluidly while keeping that ratio.
Exercise
You want a square tight crop on phones and a wide landscape crop from 64em upward. Which element do you use, and which image goes in the img element?
Show answer
Use the picture element with a source whose media is (min-width: 64em) pointing at the wide image. The img element holds the tight square crop, because the mobile-first base case is the default and the wide version is added for larger screens.