/ #html #web 

Srcset Tutorial : Responsive Image HTML

Responsive images are images that adapt to the width of screen to fit it perfectly and to improve the performance of the site.

If you like this post feel free to share it with your colleagues.

Why reponsive images?

I’m pretty sure that, until now, all the images you have inserted in your websites looks like this:

<img src="imageURL" width="360px" height="auto" max-width="100vw" />

Let’s say the image has 1024px width : 768px height.

By loading this image on a mobile with 360px width x 740px height dimension, you are trying to fit an image of 1024x768 into 360x270 of width. (if we want to resize 1024 => 360, then heightResponsive Image = 768*360/1024)

  • 1024px x 768px image size = 500-750 KB
  • 360px x 270px image size = 100 KB

You can notice that we are using an image that doesn’t fit the screen, but also it is 500% bigger than the good one.

Let’s see how we can make an image responsive.

Resources

For this example we will used 3 images called :

  • img_1024.jpg : 1024px width for big devices
  • img_512.jpg : 512px width for medium devices
  • img_320.jpg : 320px width for small devices

srcset is the solution

srcset attribute is the easiest way to make an image responsive. It can use either the device pixel ratio or the device width to choose the good image resolution that fit the device.

Format:

<img src="default_image.jpg" src="list_of_images" />

By Image width

srcset can load the image based on the image width. It will look automatically for the best image that fits the screen. It’s the easier way to make a responsive image.

<img
  src="img_512.jpg"
  srcset="img_320.jpg 320w, img_512.jpg 512w, img_1024.jpg 1024w"
/>

As defined above, the default image is img_5120.jpg. In addition, we have added 3 srcset images.

Pixel ratio

The pixel ratio defines the density of pixels in the screen. It can be calculated using : phsyical_pixels/logical_ pixels. For more information check https://www.mydevice.io

We will not go in details of this pixel ratio, but let’s consider that :

  • 1x is for small devices
  • 1.5x is for medium devices
  • 2x is for big devices
<img
  src="img_512.jpg"
  srcset="img_320.jpg 1x, img_512.jpg 1.5x, img_1024.jpg 2x"
/>

Using the srcset attribute as above, the image will load automatically the good image that fits better the current device.

Conclusion

Responsive image improves the performance of the image and loads the page faster. This can improve your SEO ranking and also the user experience.

For making things better, you can use lazy loading to load the images after the page has been totally loaded.