Things everyone should know about responsive images and srcset

The aim of responsive images is to deliver the same image in mobile and desktop view without disturbing the viewport size that is the image should look alike in every device .

Therefore this problem of responsive images can be solved by using srcset attribute in image tag or using media queries.

Both are suitable to deal with this situation but prefer to use srcset instead of media queries because media queries will take time to write but srcset does the same thing in small time and space .
The information below will explain all about srcset .

srcset
The srcset attribute is listing different resolutions of the same image from which the browser chooses the best fitting image source before loading it.
Example: srcset="ninja-1000w.jpg 1000w, ninja-500w.jpg 500w, ..."
To calculate this, the browser assumes the image fills up the full viewport width (100vw) by default, which means it uses the full width of the browser.

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="image.jpg" alt="image" srcset="<img> <descriptor>, ..., <img_n> <descriptor_n>">.

Here is an example:

srcset="image.jpg 160w, image2.jpg 320w, image3.jpg 2x"

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

  1. density descriptor–> srcset=”image.jpg, 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.
  2. width descriptor –> srcset=”image-240.jpg 240w, image-640.jpg 640w”.
    When using the w-descriptor we have to specify the default explicitly by adding a second srcset image option, with its own w-descriptor, and separating them with a comma.
  3. size descriptor–> It only makes sense if you use width descriptor.
    srcset=”image-160.jpg 160w, image-320.jpg 320w, image-640.jpg 640w, 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.So it is like using media queries in html which looks a lot easier as compared to media queries written in css .

Pros–>
1.much easier than media query
2.saves time

Cons–>
1.Browser should be updated to see the effect
2.Not all browsers support this.
At present, Edge, Safari, and iOS Safari only support a subset of the srcset specification. Firefox, Chrome, Opera, Android Browser, and the forthcoming versions of Safari and iOS Safari fully support it.

Demo can be seen on my github link

pershantgoel.github.io/imgsrcset