How to Use Picture Element in HTML for Responsive Images
Use the <picture> element to provide multiple image sources for different screen sizes or formats. Inside it, use one or more <source> tags with media queries or type attributes, followed by an <img> tag as a fallback.
📐
Syntax
The <picture> element contains multiple <source> elements and one <img> element. Each <source> specifies a different image file and conditions like screen width or image format. The browser picks the first matching <source>. The <img> acts as a fallback if none match.
This example shows how to use the <picture> element to serve a WebP image on large screens and a JPEG on smaller screens. The <img> tag provides a fallback image for browsers that don't support the <picture> element.
A responsive image that shows a large WebP image on screens wider than 600px and a smaller JPEG image on narrower screens. If the browser does not support WebP or the picture element, it shows the fallback JPEG image.
⚠️
Common Pitfalls
Not including a fallback <img> tag inside <picture> causes no image to show in unsupported browsers.
Using incorrect media queries or missing the media attribute can cause unexpected image selection.
Forgetting the alt attribute on the <img> tag harms accessibility.
Placing <source> tags in the wrong order can cause the browser to pick the wrong image.