Good tutorial with examples.
So how to properly use srcset and sizes attributes? This is the code I used for displaying Example 1 Hero images on the sample page:
<img src="hero-big.jpg" srcset="hero-small.jpg 450w, hero-medium.jpg 960w, hero-big.jpg 1500w" sizes="(max-width: 552px) 450px, (max-width: 1062px) 960px, 1500px" alt="Learnedia Hero" />
- The first line is pretty straight forward. It is a fallback option if the browser doesn’t support srcset attribute. In this case, we want big Hero image to be downloaded so the page looks good on the desktop device.
- The second line is where the magic happens. We are defining three image sources separated with a comma. But right after the image source, we define the actual width of the image using the integer representing the width in pixels with w appended. This is important because browser now knows the actual size of the image before downloading it first.
- The third line is where we declare at which viewport widths we want a particular image to be downloaded. This is done using sizes attribute. This is where people commonly make mistakes. So it is important to fully understand the sizes attribute. It doesn’t tell the browser to download a certain image based on the width of the image parent container. It tells the browser which image to download on different viewport widths.
In my example above, I am using sizes attribute to tell the browser to download image with a width of 450px on devices with viewport width up to 552px (mobile phones). The browser uses the information given within srcset attribute about the width of the image to decide which of the three images is the most appropriate. Simple, right? And effective, too.
So, browser will now use 450px image (hero-small.jpg) for mobile phones and 960px image (hero-medium.jpg) for medium devices (up to 1062px). Note that we don’t need to declare device width for the third image. We just need to declare the size of the image for that scenario (1500px) when device width is above 1062px. That’s it!