Learn Performance - Images
sizes
This demo uses the
sizes
attribute combined with
scrcset. The
srcset
attribute in this demo uses width descriptors:
srcset="../image-640.jpg 640w,../image-1280.jpg 1280w,../image-1920.jpg 1920w"
The width descriptor matches the image file's width. So the file
image-640.jpg
has a width of
640w. The width descriptors are combined with the
sizes attribute to inform the browser at what display size the
image will be displayed on different viewports.
sizes="(min-width: 540px) 640px, calc(100vw - 2rem)"
On devices with a viewport larger than 540px, the image will always be shown at 640px, while on smaller viewports it will occupy the viewport width minus 2rem.
Image details:
| File | |
| Size | |
| Intrinsic Width | |
| Intrinsic Height | |
| Display Width | |
| Display Height | |
| DPR | |
| Percentage Used |
If you look at the table above, you can observe that the image selected by the browser depends on the viewport width and not the device's DPR. If you compare this demo with the previous one, can you see which method is serving oversized or undersized images on different devices?
View Source Code
<img
alt="Photograph of a group of pedestrians crossing the street."
width="640"
height="426"
src="../image-640-uncompressed.jpg"
srcset="../image-640-uncompressed.jpg, ../image-1280-uncompressed.jpg 2x, ../image-1920-uncompressed.jpg 3x"
/>