HTML Reference ยท Embedded Content
The <picture> element
Reference for the HTML <picture> element: art direction with media queries, modern image formats with fallbacks, how <source> is chosen, and technical details.
The <picture> element lets you offer different versions of an image and have the browser choose one. It contains zero or more <source> elements followed by exactly one <img>. The browser checks the sources from top to bottom, uses the first one whose media and type match, and displays the result through the <img>.
It solves two problems that srcset alone can't: art direction (a different crop for narrow screens) and format fallback (AVIF or WebP for browsers that support them, JPEG or PNG for the rest).
<picture> <source srcset="/images/hero.avif" type="image/avif"> <source srcset="/images/hero.webp" type="image/webp"> <img src="/images/hero.jpg" alt="Hikers on a ridge at sunrise" width="1200" height="600"> </picture>
Try it
The width and height on the <source> let the browser reserve the right space for each crop, because the two files have different shapes.
Attributes
This element has no attributes of its own. It accepts the global attributes. Selection is controlled by the media, type, srcset and sizes attributes of its <source> children; alt, width, height, loading and the rest go on the <img>.
Usage notes
- The
<img>is required. It is what actually renders. Without it, nothing is shown, and itsaltis the text alternative for every source. - Order matters. The browser takes the first matching
<source>, so list the most specific media queries and the newest formats first. - Style the
<img>, not the<picture>.<picture>is just an inline wrapper. Size, border andobject-fitrules belong on the image inside. - Don't use it just for resolution switching. If all versions show the same picture at different sizes, a plain
<img>withsrcsetandsizesis simpler. - Scripts.
img.currentSrctells you which file the browser actually chose. - Dark mode. A source with
media="(prefers-color-scheme: dark)"can serve a darker variant of an illustration or logo.
Technical summary
| Content categories | Flow content, phrasing content, embedded content, palpable content |
| Permitted content | Zero or more <source> elements, followed by one <img> element, optionally intermixed with script-supporting elements |
| Tag omission | None; both the start and end tags are required |
| Permitted parents | Any element that accepts embedded content |
| Implicit ARIA role | No corresponding role |
| DOM interface | HTMLPictureElement |
| Default display | inline |
Browser support
Supported in every browser; very old browsers that don't know <picture> simply show the <img> fallback.
Related
<source>โ the alternatives inside<picture><img>โ the image that renders the chosen source<figure>โ adds a caption around a picture- Lesson: Responsive Images
- Lesson: Images
- Lesson: Performance