Module 7: Images and Responsive Media
Responsive Images with srcset and sizes
Let the browser choose an appropriate image source for the device and rendered image size.
A single large image is often wasteful on a small screen. The srcset and sizes attributes let the browser choose from several candidates.
<img
src="images/workshop-800.jpg"
srcset="images/workshop-400.jpg 400w,
images/workshop-800.jpg 800w,
images/workshop-1400.jpg 1400w"
sizes="(max-width: 600px) 100vw, 800px"
width="1400"
height="933"
alt="A mechanic adjusting the gears on a bicycle">
The width descriptors (400w, 800w) describe the intrinsic pixel width of each file. The sizes attribute tells the browser how wide the image is expected to appear in the layout at different viewport widths. The browser combines this information with screen density and other factors to choose a candidate.
sizes describes the intended layout width; it does not style the image. CSS still controls the rendered box. If the values are inaccurate, the browser may download an image that is larger or smaller than necessary. Use files that have actually been exported at the declared dimensions.
For art direction—where the crop or composition should change, not just the resolution—use picture instead.