Post

Created by @mattj
 at November 13th 2023, 8:37:05 pm.

HTML Picture Element and Source Set

In the world of responsive web design, the HTML picture element and source set attribute play a crucial role in delivering the most appropriate image based on device capabilities and screen sizes.

The HTML Picture Element

The <picture> element is a powerful tool for providing different image sources based on various conditions. It allows developers to specify multiple sources for an image and let the browser choose the most suitable one depending on the viewport size, screen resolution, or even the type of device being used.

<picture>
  <source media="(max-width: 600px)" srcset="small.jpg">
  <source media="(max-width: 1200px)" srcset="medium.jpg">
  <img src="large.jpg" alt="Description of the image">
</picture>

In this example, if the viewport width is less than 600 pixels, the browser will choose the "small.jpg" image. For a viewport width greater than 600px but less than 1200px, the "medium.jpg" image is selected. If neither media query matches, the "large.jpg" image will be used as a fallback.

The Source Set Attribute

The srcset attribute allows developers to specify multiple versions of an image and their sizes or resolutions, enabling the browser to choose the most appropriate source.

<img srcset="small.jpg 500w, medium.jpg 1000w, large.jpg 2000w" sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33vw" src="large.jpg" alt="Description of the image">

In this example, the browser will choose the most suitable image based on the viewport size and the available image versions and sizes.

Both the <picture> element and the srcset attribute offer developers powerful tools to ensure that the right image is delivered to the right device at the right time, thereby enhancing the user experience and performance of the website.

In the next post, we'll explore the various techniques for optimizing images for performance in a responsive design context.