The
<picture>element in HTML is used to display responsive images that automatically adjust to different devices and screen sizes. It allows you to define multiple image sources, and the browser chooses the most suitable one based on screen width, resolution, or file type.
This helps improve loading speed and visual quality, especially on mobile and high-resolution displays.
HTML <picture> Syntax
<picture>
<source srcset="https://picsum.photos/id/237/400" media="(min-width: 800px)">
<source srcset="https://picsum.photos/id/237/200" media="(min-width: 500px)">
<img src="https://picsum.photos/id/237/100" alt="A scenic mountain view">
</picture>
Explanation
- The
<picture>tag acts as a container for multiple image sources. - Each
<source>element specifies an image file and a condition for when it should be used. - When the screen is 800px or wider, the large image is shown.
- For screens between 500px and 799px, the medium image is displayed.
- On smaller screens, the browser shows the mobile image.
- The browser checks these sources from top to bottom and displays the first one that matches the current device or screen width.
- The
<img>tag inside<picture>serves as a fallback image if none of the conditions match.
Using Different Image Formats
The <picture> tag can also be used to provide images in multiple formats.
Modern browsers can load newer, more efficient formats like WebP, while older browsers fall back to JPEG or PNG.
<picture>
<source srcset="https://picsum.photos/id/46/400.webp" type="image/webp">
<source srcset="https://picsum.photos/id/237/400.jpg" type="image/jpeg">
<img src="https://picsum.photos/id/237/100.jpg" alt="Beautiful landscape">
</picture>In this example:
- Browsers that support WebP will load photo.webp.
- Others will automatically fall back to photo.jpg.
Advantages
- Displays the best image for the user’s device.
- Reduces bandwidth and improves loading speed.
- Provides flexibility for responsive design.
- Maintains backward compatibility with older browsers.
Browser Support
All modern browsers including Chrome, Firefox, Safari, Edge, and Opera support the <picture> element.
Older browsers that don’t support it will still display the fallback <img> tag.
Conclusion
The <picture> element is a powerful tool for delivering responsive and optimized images on the web.
By using it with the srcset, media, and type attributes, you can control how images appear across different devices, ensuring both speed and quality.
It’s an essential part of modern HTML for performance-focused websites.