Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

<picture>

A container for several versions of an image: the browser picks a matching `<source>` or falls back to `<img>`.

Syntax

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

Examples

A different crop on narrow screens (resize the window):

<picture>
  <source media="(max-width: 500px)" srcset="/media/photo-200x200.jpg">
  <img src="/media/photo-600x200.jpg" alt="Coffee beans" style="max-width: 100%;">
</picture>

A separate image for the dark theme:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="/media/photo-200x200.jpg">
  <img src="/media/photo-400x250.jpg" alt="A cup of coffee" width="200">
</picture>

Notes

The <img> inside is required and goes last: it is what displays the image, while <source> only swaps its address. Styles and alt go on the <img>. If you only need different resolutions of the same picture, srcset on <img> itself is enough.

See also

  • <source> — One of the file versions for `<video>`, `<audio>` or `<picture>`.
  • <img> — An image.
  • srcset — Several files of one image in different sizes: the browser picks the one that fits the screen.

Related recipes

In the tutorial

  • Responsive images — How pictures adapt to the screen — max-width, aspect-ratio, object-fit, the srcset and sizes attributes, the picture element.

Thanks for reading!

Donate to the site — we work hard for you.