<picture>

A container for several versions of an image. The browser picks the one that best fits the screen and format.

Display
inline
Closing tag
Required
Permitted content
<source> elements, and one <img> at the end
On this page

Example

#
HTML
<picture>
  <source
    media="(min-width: 480px)"
    srcset="/collections/covers/vibe-coding.webp"
    width="300"
    height="200"
  >
  <img
    src="/collections/cursor.png"
    alt="A vibe coding course with the Cursor editor"
    width="96"
    height="96"
  >
</picture>
Preview

On a screen wider than 480 pixels you see the course cover, and on a narrower one just the logo. Narrow the window or open the page on a phone to see the change.

Definition and usage

#

The <picture> element lets you provide several image sources, and the browser picks the first one that matches. Inside you place <source> elements with conditions and one <img> element, which is required and acts as the default version.

It is used in two situations. The first is art direction: a panoramic photo on a wide monitor, and a tighter crop or just an icon on a phone. The second is modern formats: the browser takes an AVIF or WebP file if it supports it, and an older one gets a JPEG.

The image is always displayed by the <img> element, and <source> only swaps its address. That’s why you set the alt, width, and height attributes and CSS styles on the <img>, not on the <picture>. If you only want to offer the same image in several resolutions, srcset on the <img> alone is enough.

Syntax

#
Syntax
<picture>
  <source media="…" srcset="…">
  <img src="…" alt="…">
</picture>

Attributes

#

This element has no attributes of its own. It supports the global attributes, such as class, id and hidden.

More examples

#
Modern formats with a JPEG fallback
HTML
<picture>
  <source srcset="/img/kurs-python.avif" type="image/avif">
  <source srcset="/img/kurs-python.webp" type="image/webp">
  <img src="/img/kurs-python.jpg" alt="A laptop with a Python code editor open" width="640" height="427">
</picture>

The browser checks the sources in order and takes the first one whose format it supports. That’s why the lightest format (AVIF) comes first, and JPEG comes last as the version for everyone.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Without an <img> inside <picture>, nothing is displayed. <source> elements alone show nothing.
  • With different crops, provide width and height on each <source> too, so the browser reserves space with the right proportions.
  • Don’t use <picture> for ordinary images in several resolutions. <img srcset="…" sizes="…"> is enough.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.