What is the srcset attribute in an IMG tag and how to use it?

In short, Srcset is a new attribute which allows you to specify different kind of images for different screen-sizes/orientation/display-types. The usage is really simple, you just provide a lot of different images separating them with a comma like this: <img src="https://stackoverflow.com/questions/19634463/image.jpg" alt="image" srcset="https://stackoverflow.com/<img> <descriptor>, https://stackoverflow.com/..., https://stackoverflow.com/<img_n> <descriptor_n>">. Here is an example: srcset="https://stackoverflow.com/image.jpg 160w, https://stackoverflow.com/image2.jpg 320w, https://stackoverflow.com/image3.jpg 2x"

This is a longer answer which explains things in more details.

Difference between srcset and picture. Both srcset and picture does approximately the same things, but there is a subtle difference: picture dictates what image the browser should use, whereas srcset gives the browser a choice. A lot of things can be used to select this choice like viewport size, users preferences, network condition and so on. The support for srcset is pretty good and almost all current browsers more or less support it. Situation with a picture element is a little bit worse.

Descriptors are just a way to show what kind of image is hidden behind the resource. There are various kinds of descriptors:

  • density descriptor. srcset="https://stackoverflow.com/image.jpg, https://stackoverflow.com/image-2X.jpg 2x"
    The display density values—the 1x, 2x, etc.—are referred to as display density descriptors. If a display density descriptor isn’t provided, it is assumed to be 1x. Good variant to target retina displays.
  • width descriptor. srcset="https://stackoverflow.com/image-240.jpg 240w, https://stackoverflow.com/image-640.jpg 640w". I am sure this is self explanatory. The only problem is that by itself width descriptor is not really helpful. Why? read here
  • size descriptor, which only makes sense if you use width descriptor. srcset="https://stackoverflow.com/image-160.jpg 160w, https://stackoverflow.com/image-320.jpg 320w, https://stackoverflow.com/image-640.jpg 640w, https://stackoverflow.com/image-1280.jpg 1280w" sizes="(max-width: 480px) 100vw, (max-width: 900px) 33vw, 254px">. The instructions for the browser would look like this: (max-width: 480px) 100vw — if the viewport is 480 pixels wide or smaller, the image will be 100% of the viewport width. (max-width: 900px) 33vw — if the viewport is 480 pixels wide or smaller, this rule will never be reached because of the previous media condition. And 254px is when there is no media condition listed, the length is assumed to be a default value used when none of the other media conditions are met.

Just for completeness will add here that there is an image-set() attribute for a background image in CSS and some other helpful link here

Leave a Comment