HTML Advanced: Accessible, Findable, Fast Pages
Responsive and Fast Images
In this lesson you will
- Explain why one image size does not fit every screen
- Use srcset and sizes to offer several image sizes
- Use picture for different formats, and loading lazy
Introduction
A giant photo that looks great on a big monitor wastes a phone's data and slows the page. A tiny photo looks blurry on a big screen. Responsive images let you offer several versions and let the browser choose the best one.
The simple explanation
You list the image files you have, say how wide the image will be shown, and the browser picks.
Images are usually the heaviest part of a page, so this is one of the biggest speed wins you can make.
srcset and sizes
srcset lists files with their real widths, written with w. sizes says how wide the image will be displayed.
HTML
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 800px) 800px, 100vw"
alt="A mountain lake at sunrise"
width="800" height="533">Read sizes like this: "On screens 800px or wider, the image is shown 800px wide. Otherwise it fills the whole width (100vw)." The browser combines that with the screen's pixel density and picks a file.
The plain src is the fallback for browsers that do not understand srcset.
Quick quiz
What does the w in 400w describe?
The picture element
Use picture when you want to serve a different format or a different crop. The browser uses the first source it supports, and falls back to the img.
HTML
<picture>
<source srcset="photo.avif" type="image/avif">
<source srcset="photo.webp" type="image/webp">
<img src="photo.jpg" alt="A mountain lake at sunrise" width="800" height="533">
</picture>Modern formats such as WebP and AVIF are often much smaller than JPEG at the same quality.
Width, height and lazy loading
- Always set
widthandheight. The browser then reserves the right space and the page does not jump while images load. - Add
loading="lazy"to images far down the page. They are fetched only when the visitor scrolls near them.
HTML
<img src="footer-photo.jpg" alt="Our team" width="600" height="400" loading="lazy">Do not lazy-load the main image at the top of the page, because that makes it appear later.
Quick quiz
Which image should NOT use loading=lazy?
Try it yourself
This page shows an image with set dimensions and lazy loading. Change the width and height, and see how the result changes.
The style line lets the image shrink on small screens while keeping its shape.
Summary
srcsetandsizeslet the browser choose the best file for the screen.pictureoffers different formats or crops.- Set
widthandheight, and lazy-load images below the fold, but not the top image.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading