Sub topic 12
Serve images that fit every screen
This chapter covers how to deliver images that look sharp on any device without wasting bandwidth. It assumes you can write a basic HTML page, link a stylesheet, and use media queries and max-width from the earlier chapters. The chapter adds srcset, sizes, the picture element, intrinsic dimensions, lazy loading, and the CSS that keeps images inside their containers.
Why one image file is not enough
A single photo.jpg forces a trade-off. If the file is large, phones on slow connections download far more pixels than they can show. If it is small, it looks blurry on a wide monitor or a high-density screen.
Two things vary between devices:
- Layout width. The image may be 320 CSS pixels wide on a phone and 400 CSS pixels wide on a desktop.
- Pixel density. A CSS pixel is a layout unit. A high-density display (often called "2x" or "Retina") draws two or more device pixels per CSS pixel, so an image shown at 400 CSS pixels wide needs about 800 real pixels to look sharp.
Responsive images let you offer several files and give the browser enough information to choose one. The browser knows the screen width, the density, and often the network conditions. You do not.
Start with a flexible base
Before adding multiple files, make sure one image cannot break your layout. Add this rule to your stylesheet:
img {
max-width: 100%;
height: auto;
}max-width: 100% stops the image from growing wider than its container. height: auto keeps the aspect ratio when the width shrinks. Without height: auto, an image with a height attribute would be squashed.
Offer several widths with srcset and sizes
Here is the image from the page skeleton.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="(min-width: 48rem) 400px, 100vw"
width="800"
height="800"
loading="lazy"
alt="Portrait of Jane Doe at her desk">Each attribute has a job.
| Attribute | Purpose |
|---|---|
| `src` | The fallback file. Browsers that do not understand `srcset` use it. |
| `srcset` | A list of candidate files. The `w` number is each file's real width in pixels. |
| `sizes` | How wide the image will be displayed in the layout, so the browser can pick a candidate. |
| `width` and `height` | The file's intrinsic dimensions, used to reserve space. |
| `loading` | When to fetch the file. |
| `alt` | A text description for people who cannot see the image. |
How the browser chooses
The browser reads sizes first, left to right, and takes the first condition that matches. In the example:
- If the viewport is at least
48remwide, the image displays at400px. - Otherwise it displays at
100vw, the full viewport width.
Then it multiplies that display width by the device pixel density and picks the smallest candidate in srcset that covers the result. On a 360px-wide phone at 2x density, the needed width is 720 pixels, so it chooses photo-800.jpg. On a 1280px-wide desktop at 1x density, the needed width is 400 pixels, so it chooses photo-400.jpg. On the same desktop at 2x density, it needs 800 pixels and chooses photo-800.jpg.
The choice is a hint-based decision. Browsers may pick a larger file than the minimum, for example if one is already in the cache. Do not rely on a specific file being chosen.
Common mistakes with sizes
- Leaving out
sizes. If you usewdescriptors withoutsizes, the browser assumes the image is100vwwide. On a layout where the image is small, it will download an oversized file. - Writing
sizesthat does not match the CSS. The browser trustssizes. If your CSS makes the image 300px wide butsizessays100vw, the browser still downloads the large file. - Using a percentage in
sizes. Values must be lengths such as400px,50vworcalc(100vw - 2rem). A percentage is not valid. - Mislabeling widths. The
wvalue must be the file's true pixel width. A wrong label leads to wrong choices.
Density descriptors for fixed-size images
When an image has a fixed display size, such as a 100px avatar, skip sizes and use x descriptors:
<img
src="avatar-100.jpg"
srcset="avatar-100.jpg 1x, avatar-200.jpg 2x"
width="100"
height="100"
alt="Jane Doe">Do not mix w and x descriptors in one srcset. Use w plus sizes for fluid images, and x for fixed ones.
Reserve space with width and height
The width and height attributes do not force the displayed size, because your CSS rule height: auto overrides the height. Modern browsers use the two numbers to compute an aspect ratio before the file arrives, and they reserve a box of that shape in the layout.
Without them, the page renders text first, then jumps down when the image loads. This jump is called layout shift, and it hurts reading and scores badly on performance checks.
Use the real pixel dimensions of the src file. If the image is 800 by 800, write width="800" height="800". Do not write width="100%", since these attributes take unitless integers.
Lazy loading
loading="lazy" tells the browser to delay the download until the image is near the viewport. This saves data for images far down the page.
Follow these rules:
- Use
loading="lazy"for images below the first screen. - Leave it off for the image that appears at the top of the page, since delaying it slows the first view. The portrait in the skeleton is the exception to this rule if it sits in the opening section, so remove
loading="lazy"there if it is visible on load. - Always include
widthandheightwith lazy images, or the space will not be reserved.
You can also add decoding="async" to let the browser decode the image off the main path. It is optional and safe.
Different crops with the picture element
srcset gives the browser different sizes of the same image. Sometimes you want a different image: a tight crop on a phone and a wide scene on a desktop. This is called art direction. Use picture:
<picture>
<source media="(min-width: 48rem)" srcset="banner-wide.jpg">
<img src="banner-narrow.jpg" width="600" height="400" alt="Jane's desk with a laptop and notebook">
</picture>The browser checks each source in order and uses the first one whose media matches. The img is required. It is the fallback and also carries the alt, width, height and loading attributes.
Unlike sizes, a media condition is a command, not a hint. The browser must follow it.
Choosing a format
You can also use picture to offer modern formats with a fallback:
<picture>
<source type="image/avif" srcset="photo-800.avif">
<source type="image/webp" srcset="photo-800.webp">
<img src="photo-800.jpg" width="800" height="800" alt="Portrait of Jane Doe at her desk">
</picture>The browser skips any source whose type it cannot decode. AVIF and WebP usually give smaller files than JPEG at similar quality. Put the smallest format first and the most widely supported format in the img.
Keep images from distorting
If you set both a width and a height in CSS, the image may stretch. Use object-fit to control how the picture fills its box:
.project-card img {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}object-fit: cover fills the box and crops the overflow. contain shows the whole image and leaves empty space. Setting aspect-ratio gives every card image the same shape, which keeps a grid of project cards tidy.
Choosing image files
Resizing is part of the work. A browser cannot make a 4000px photo small on disk.
- Export widths that match your
srcsetlist, such as 400, 800 and 1200. - Use JPEG or WebP for photographs, and PNG or SVG for logos and flat graphics.
- Compress each file. Quality settings of 70 to 80 percent are usually hard to tell from the original.
- Name files by width, as in
photo-400.jpg, so mistakes are easy to spot.
Testing your work
- Open the browser's developer tools and go to the Network panel. Filter by images.
- Reload at a narrow width and note which file loaded.
- Widen the window, switch the device pixel ratio in the device toolbar, and reload. The chosen file should change.
- In the Elements panel, check the
currentSrcproperty of the image to see which candidate won. - Disable the cache while testing, or the browser may reuse an earlier file.
Exercise
A page shows a project image at 50vw wide on screens wider than 60rem and at 100vw on narrower screens. You have files at 400, 800 and 1600 pixels wide. Write the srcset and sizes attributes. Then say which file a 1200px-wide viewport at 2x density would most likely load.
Show answer
srcset="proj-400.jpg 400w, proj-800.jpg 800w, proj-1600.jpg 1600w" and sizes="(min-width: 60rem) 50vw, 100vw". At 1200px wide, the image displays at 50vw, which is 600 CSS pixels. At 2x density the browser needs 1200 pixels, so the smallest file that covers it is the 1600w file.
Exercise
Why should you set width and height on an img even though your CSS sets height: auto?
Show answer
The browser uses the two values to work out the aspect ratio and reserve space before the file downloads. This prevents layout shift when the image appears.