Why would you use a srcset and sizes attributes in an image tag?


Using the srcset and sizes attributes, you can serve multiple sizes of the same image. The browser does the calculation and decides which image to select and display to the user.

srcset attribute

srcset attribute defines a set of images and their respective sizes from which the browser can decide which image to select depending on the size of the screen. Image information inside the srcset attribute is separated using a comma.

<img srcset="https://via.placeholder.com/150 150w,
             https://via.placeholder.com/300 300w"
     sizes="(max-width: 500px) 150px,
     alt="Placeholder Image" 

sizes attribute

Sizes define the media conditions according to which browser will select a particular image defined in the srcset attribute.

It consists of two parts:

  1. media conditions: The condition according to which browser will make the decision to select a particular image.

  2. width of the slot: The width of the space on the screen which the image will take when the media condition is true.

You can also define a default value for image slot without a media condition. The browser will make the calculation and select the best image.

Fallback and Support

The support of srcset and sizes attributes are good. If the browser doesn't support these attributes, it will simply load images from the src attribute of <img> tag.

Share and support us

Share on social media and help us reach more people