Skip to main content

HTML Images and Media

HTML Picture Element

Written by Updated HTML Picture Element exercises

The picture element lets the browser choose between several versions of an image: a smaller file for phones, a wider crop for desktops, a modern WebP file where it is supported. The img tag inside is the fallback and the part that is actually displayed.

You list <source> elements in order; the browser uses the first one whose conditions match, and falls back to the <img> if none do. The alt text goes on the <img>, and only there. The plain <img> attributes are covered in the img tag.

HTML <picture> Syntax

Picture Tag Example

html

<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>
  • On screens 800px or wider, the browser loads the 400-pixel version.
  • From 500px, the 200-pixel version.
  • On anything smaller, the <img> fallback.

Change the preview width to see the image change. This is called art direction: different images, or different crops, for different screens.

Using Different Image Formats

A second use is offering a modern file format with a safe fallback:

Various Image Format Example

html

<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>

Browsers that understand WebP load the first source. Others try the JPEG. Very old browsers that do not know <picture> at all simply show the <img>. Today, AVIF and WebP are both widely supported and much smaller than JPEG.

picture or just srcset?

If you only want the same image at different sizes, you do not need <picture>. An <img> with srcset and sizes is simpler, and lets the browser pick the best size itself. Use <picture> when you need a different crop for different screens, or different file formats.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesPartially

Good to know

  • Always include the <img>. Without it, nothing is displayed at all.
  • Put width, height and alt on the <img>, not on the sources.
  • Order matters: the browser takes the first matching source, so list the most specific or most modern one first.

HTML Picture Element exercises

Image in a picture

Put the image https://html5andcss3.org/samples/star.svg with the alternative text Star in a picture element.

Result

Check your answer to see it here.