Here is a detailed guide on srcset along with code samples.
srcset
allows you to define a list of different image resources along with size information so that browser can pick the most appropriate image based on the actual device’s resolution.
Each comma-separated item in srcset
has:
- Image URL, e.g.
http://ik.imagekit.io/demo/default-image.jpg
or relative path /demo/default-image.jpg
- An empty space
- The actual width of the image or display density:
- Either using display density descriptor, for example,
1.5x
, 2x
etc.
- Or, using width descriptors, for example,
450w
. This is the width of the image in pixels.
Using display density descriptor
The syntax for display density descriptors is straightforward. srcset
provides a comma-separated list of image resources along with display density it should be used, for example1x
, 2x
etc.
<img src="image.jpg"
srcset="image.jpg,
image_2x.jpg 2x"
/>
Live demo - https://imagekitio.github.io/responsive-images-guide/srcset-density.html.
Using width descriptor
The syntax is similar to the display density descriptor, but instead of display density values, we provide the actual width of the image.
<img src="image.jpg"
srcset="small.jpg 300w,
medium.jpg 600w,
large.jpg 900w"
/>
This lets the browser pick the best image
Using width descriptor allows the browser to pick the best candidate from srcset
based on the actual width needed to render that image on that particular display at runtime.
Note that display pixel density is also taken into account by the browser while calculating the required width. 😎
For example, assuming an image takes up the whole viewport width - On a 300px wide screen with DPR 2, the browser will pick medium.jpg
because it needs a 300x2=600px wide image. On a 300px wide screen with DPR value 3, the browser will select large.jpg
because it needs a 300x3=900px wide image.
Demo - srcset with width descriptor
Let see this in action with a live demo - https://imagekitio.github.io/responsive-images-guide/srcset-width.html.