The choosing logic in img srcset

I miss the old days when <img> has only a few simple attributes and you only need to know that src is used to store the url of the image.

Nowadays, img becomes much more complex. More and more attributes are added and only the inventor knows how to use them accurately. This post has a good explanation about the srcset attribute but the content is lengthy and tedious. I try to  give you a simple description of how to use the srcset, sizes attributes.

I will use the same demo example here:

<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">

Now the new attributes make it possible to show different images on different devices. With the device size at hand, the browser scans the conditions listed in the sizes attribute and chooses the slot size following the first condition that is met.  On devices with screen width less than 600px, the browser chooses a slot size of 480px. The slot size is nothing but an intermediate value. It is not the displayed size of the image on the screen. The slot size is just used to match an image in the srcset attribute. The image whose size is closest to the slot size is selected to be shown on the screen. The size of every image in the srcset attribute is specified next to the image name, and its unit is w instead of px although it has the same meaning of px.  Only the image width is specified.  You may wonder why the image width needs to be specified considering the fact that it is the intrinsic attribute of the image. That is because the browser won’t (although it is able to) fetch every image listed in  srcset and analyze its dimension. That is exactly the reason that the srcset/sizes attributes are invented – to save bandwidth. So the browser simply relies on the values you provide as the widths of the images, even you provided wrong values. In this case, the browser sees elva-fairy-480w.jpg has the width 480w which is closest to the slot size 480ps so it fetches elva-fairy-480w.jpg and shows it on the screen. If none of the conditions in sizes is met, i.e., screen width greater than 600px, the browser will choose the default slot size(800px), then select elva-fairy-800w.jpg to show on the screen.

 

 

Leave a Reply