Here is a detailed guide on using Srcset with sizes.
sizes
attribute contains a comma-separated list. Each item in the list describes the size of the image in relation to the viewport.
Using the sizes
attribute with srcset
provides the browser with enough information to start downloading the right image as soon as it sees an <img>
tag in HTML without waiting for styles sheets to complete downloading and parsing.
Why do we need sizes?
If you are wondering why the browser is not aware of how big the image will render, checkout how the browser loads a web page.
The syntax:
<img src="image.jpg"
srcset="small.jpg 300w,
medium.jpg 600w,
large.jpg 900w"
sizes="(max-width: 300px) 100vw, (max-width: 600px) 50vw, (max-width: 900px) 33vw, 900px"
/>
Each comma-separated item in sizes
has:
- Media conditions, for example,
(max-width: 300px)
- It describes a possible state that the screen can be in. (max-width: 300px)
means when the viewport width is 300 CSS pixels or less. It is similar to media queries but with some limitations. You cannot use screen
or print
.
- An empty space.
- The width of the image element when the media condition is true. You can provide an absolute length (px, em) or a length relative to the viewport (vw), but not percentages.
Demo - srcset with sizes
Let’s see this in action with a live demo - https://imagekitio.github.io/responsive-images-guide/srcset-sizes.html
The layout is such that:
- If viewport width is above 900px, each image takes a fix 225px width.
- Upto 900px, each image takes up 33vw i.e. 33% width of total viewport width.
- Upto 700px, each image takes up 50vw i.e. 50% width of total viewport width.
- Upto 400px, each image takes up 100vw i.e. the whole viewport width.
HTML markup of a single image element looks like this:
<img src="https://ik.imagekit.io/ikmedia/women-dress-1.jpg"
srcset="https://ik.imagekit.io/ikmedia/women-dress-1.jpg?tr=w-225 225w,
https://ik.imagekit.io/ikmedia/women-dress-1.jpg?tr=w-300 300w,
https://ik.imagekit.io/ikmedia/women-dress-1.jpg?tr=w-350 350w,
https://ik.imagekit.io/ikmedia/women-dress-1.jpg?tr=w-640 640w"
sizes="(max-width: 400px) 100vw, (max-width: 700px) 50vw, (max-width: 900px) 33vw, 225px">
Let’s see what happens at different screen size and DPR values -
