Images are some of the most important pieces of information on the web, but over the web history, they haven’t been very adaptable at all. Everything about them has been stubbornly fixed: their size, format and crop, all set in stone by a single
src. HTML authors began to really feel these limitations when high-resolution screens and responsive layouts.
Why using srcset and sizes?
There are two advantages
- Serving better images to the user
- Improving the website loading time
sizes it is possible to offer multiple sizes of the same image. The browser does the calculation and chooses the best size to display to the user. Browser support of
sizes is good and the fallback is perfect – http://caniuse.com/#search=srcset.
The browser not only takes into account the width of the screen (viewport width), but also the pixel density. Whether a user is viewing your website on a desktop screen with low resolution or a tablet screen with high resolution, the browser chooses the best size.
Because you can offer multiple sizes of the same image, you can improve the loading time of your site. It’s no longer needed to serve that big hero image on a small screen. With
sizes you can offer a smaller size which will be used by the browser. This results in a faster website.
How srcset and sizes works
An example of an
<img> tag with the new
<img alt="image alt text" src="medium.jpg" srcset="small.jpg 240w, medium.jpg 300w, large.jpg 720w" sizes=“(min-width: 960px) 720px, 100vw">
Let walk through each parts
The familiar way to specify the location of your image. Browsers that do not support
sizes will fallback to
srcset="small.jpg 240w, medium.jpg 300w, large.jpg 720w"
scrset you specify a list of the image in different sizes. In this example we have three sizes of the same image. Behind the file name of each image you specify the width in pixels (
w of width). For example,
small.jpg 240w means that this image is 240px wide.
sizes="(min-width: 960px) 720px, 100vw"
sizes you specify the size of the image and in which situation it must be displayed. This is done by a combination of a media query and the width of the image. The above code for
sizes does the following, if viewport width
- Equals to 960px or greater than show the image with a width of 720px.
- Smaller than 960px than show the image as wide as the viewport (100vw means 100% of the viewport width).
What happen if
sizes="(min-width: 960px) 540px, 100vw". Now you may notice that in our example of
srcset there’s no image with a width of 540px. That’s not a problem. The browser will select the best image available upwards in size. In this case, large.jpg will be used with a width of 720px.