Using the HTML `` Element for Responsive Images: Optimizing Image Delivery for Different Devices

Learn how to use the HTML `` element to serve different images based on screen size and other factors for responsive web design. This tutorial explains ``'s functionality, its use with `` and `` elements, and how it improves website performance and user experience by optimizing image delivery.



Using the HTML `` Element for Responsive Images

Understanding Responsive Images

Responsive web design ensures that your website looks good on all devices (desktops, tablets, smartphones). A key part of this is using responsive images—images that automatically adjust to different screen sizes. The HTML `` element provides a flexible and efficient way to serve different images based on screen size and other factors. This improves performance by avoiding the downloading of unnecessarily large images to smaller screens.

How the `` Element Works

The `` element contains one or more `` elements, each having an associated media query in the `media` attribute. The browser checks these media queries against the user's device and viewport size to select the most suitable image to display. The browser will use the first source element whose `media` condition matches, ignoring any subsequent sources. A fallback `` element is required. This image will display if the browser doesn't support the `` element or none of the other image sources are appropriate. The fallback `` must always be the last element inside the `` element.

Example: Responsive Image with ``

<picture>
  <source media="(min-width: 650px)" srcset="large.jpg">
  <source media="(min-width: 465px)" srcset="medium.jpg">
  <img src="small.jpg" alt="Description of image">
</picture>

In this example, the browser will select `large.jpg` for screens 650px or wider, `medium.jpg` for screens between 465px and 649px, and `small.jpg` for screens smaller than 465px. If the browser doesn’t support the `` element, it will use `small.jpg`.

Browser Support for ``

The `` element is well-supported by most modern browsers.

Browser Version
Chrome 38.0
Edge 13.0
Firefox 38.0
Opera 9.1
Safari 11.0

Attributes of the `` Element

The `` element doesn't have attributes of its own, but the inner `` and `` elements use several attributes:

  • src (in ``): The URL of the image.
  • srcset (in `` and ``): Specifies multiple image sources for different screen sizes.
  • media (in ``): Specifies the media conditions (screen size, device type, etc.).
  • type (in ``): Specifies the MIME type of the image.
  • sizes (in ``): Provides further information to help the browser determine the optimal image size.

The `` element also supports standard HTML global and event attributes.