HTML & CSSMedium
What is the <picture> tag?
<picture> wraps one or more <source> elements and a fallback <img>, letting the browser choose the best image file for the situation: a modern format it supports (AVIF, WebP), or a different crop for a different screen size or color scheme (art direction). The <img> inside is required and is what actually renders.
Two main use cases
- Format switching: offer AVIF, then WebP, then JPEG. The browser picks the first
<source>whosetypeit supports. - Art direction: show a tightly cropped portrait image on phones and a wide landscape image on desktops, chosen by each
<source>'smediaquery.
How selection works
<source>elements are evaluated in order; the first match wins.- Each
<source>can havesrcset,sizes,media,type, andwidth/height(useful when crops have different aspect ratios). alt,loading,decoding,fetchpriorityand CSS classes go on the<img>.media="(prefers-color-scheme: dark)"can swap in a dark-mode image.
When you do not need it
If you only need different resolutions of the same image, <img srcset sizes> alone is enough. Use <picture> for formats or art direction.
In frameworks
Next.js <Image> serves modern formats automatically through its image optimizer, so you rarely write <picture> by hand there.
Code example
html
1<style>2 body { font-family: system-ui; }3 img { width: 100%; max-width: 640px; height: auto; border-radius: 8px; }4</style>5<picture>6 <!-- Art direction: square crop on narrow screens -->7 <source media="(max-width: 600px)"8 srcset="https://picsum.photos/id/1015/600/600"9 width="600" height="600">10 <!-- Modern format first, when supported -->11 <source type="image/webp"12 srcset="https://picsum.photos/id/1015/1280/640.webp">13 <!-- Fallback, and the element that actually renders -->14 <img src="https://picsum.photos/id/1015/1280/640"15 width="1280" height="640"16 alt="River winding through a forested valley"17 decoding="async">18</picture>19<p id="out"></p>20<script>21 const img = document.querySelector("picture img");22 const show = () => (document.getElementById("out").textContent = "Browser chose: " + img.currentSrc);23 img.complete ? show() : img.addEventListener("load", show);24 addEventListener("resize", () => setTimeout(show, 300));25</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.