Responsive images with HTML

It's common among web developers to use CSS or event Javascript to display images correlated to the browser's viewport. However, as the browser begins to download images referenced in a page before the CSS/JS is interpreted, this incurs a performance penalty.

Responsive images are not just about design, but about performance too. Think about it, does it make sense for a mobile phone user with a small screen to download the same images that display in high definition on a large Mac Retina display?

The purpose of responsive images is to serve the right image to the right device.

So a better solution for responsive images is often to use HTML to specify the correct image.

Traditionally, the <img> tag was used for displaying images. The image tag could only reference one single image:

<img src="puppy-800w.jpg" alt="puppy">

However the srcset property allows you to reference several images. You reference several images. You can also include a particular density inside the HTML to inform the browser which image should be used for a particular device.

Here is an example of that:

<img srcset="puppy-small-1x.jpg 1x,
             puppy-small-2x.jpg 2x"
     src="puppy-small-1x.jpg" alt="Puppy">

As you can see, after the image file location is the pixel density that the image should be used for for example 1x, or 2x.

It's also a good idea to include the src property for browsers that are unable to handle srcset.

Resources:

https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images