picture
<picture> <source media="(min-width: 600px)" srcset="desktop-600x300.png 600w, desktop-1200x600.png 1200w" sizes="50vw"> <img alt="A test responsive image" src="mobile-1200x1200.png" srcset="mobile-600x600.png 600w, mobile-1200x1200.png 1200w" sizes="80vw"/> </picture>
The <picture>
element adds a number of features to your responsive images:
The syntax inside <source>
elements is the same as when using srcset
and
sizes
in a regular <img>
.
Media conditions specified in <picture>
<source>
s must be obeyed, this means
it's safe to use <picture>
for art direction. This includes using images of different intended
sizes and aspect ratios in different <source>
s.
(Note this is in contrast to
srcset
values which are only suggestions and the browser may not always use as specified.)
The first matching <source>
element in <picture>
wins. This means order
is important depending on how you write your media conditions.
The final entry in <picture>
is an <img>
. If none of the
<source>
elements match, or if the browser doesn't support <picture>
, then
this fallback <img>
is used.
You can lazy load a <picture>
by simply adding the normal loading="lazy"
attribute
to the fallback <img>
element.
<picture>
<source>
s that matches:
<source>
s list from the top, none of the conditions match.<img>
.sizes
that matches:
srcset
that matches:
srcset
attribute is then consulted to find the closest matching image. In this case
there is a width descriptor of 1200w
which is the smallest
image which fits the size. This results in the corresponding
1200x1200.png
image being chosen.
<picture>
<source>
s that matches:
<source>
s list from the top the first one matches, so we'll use that.
sizes
that matches:
srcset
that matches:
srcset
attribute is then consulted to find the closest matching image. In this case
there is a width descriptor of 600w
which is the smallest
image which fits the size. This results in the corresponding
600x300.png
image being chosen.