Last updated on June 1, 2020
Srcset is a property that we can use with img tag. It lets us list a set of images which we want to load at different resolutions for an image. For example:
<img id="sfo" src="images/foo-500_small.jpg" srcset="images/foo-1600_large.jpg 1600w, images/foo-1000_large.jpg 1000w, images/foo-800_medium.jpg 800w, images/foo-500_small.jpg 500w" sizes="50vw" alt="Some description about the image">
The browser chooses one from the list and then fetches the image based upon the viewport dimensions, the image size relative to the viewport, the pixel density of the user’s device, and the source file’s dimensions.
By default, the browser will choose the first image if we don’t specify a window size.
We can add a width descriptor along with the image path to specify the width of each image in pixels. The browser then uses these widths to fetch the matching image based on its window size. The browser will select the image with the smallest width that is actually larger than the viewport width.
We can also optionally specify a pixel density instead of a width. However, we cannot specify pixel densities and widths within the same srcset attribute.
Note: If a larger version of an image is already available in the browser (HTTP) cache, some browsers might use that image even if it is not the one specified in srcset (because if the browser already has a higher resolution image stored locally, why not use it?).
We can also add a sizes attribute to specify an image size to tell the browser beforehand if the image will be displayed at a different size. By default, the browser assumes the image will be displayed at 100% of the viewport width.
Srcset is a great option and works nicely. Browsers calculate the viewport width and load the specified image according to the calculated width.
In short, we give the browser a couple of options, and the browser does its calculation and loads the image that it finds fit according to the calculation.
We can also use the picture, and source element, combined with media queries, to change the image source as the window is resized.
Picture tags also let us specify different images for different screen sizes. It allows us to control which image to show on what screen sizes explicitly.
To learn more about repsonsive images you can checkout this codelab from google.