-x
syntax to set densityHere are the basics of using <picture>
with the -x
syntax. Remember that the <picture>
is really just a src
-selecting wrapper for the <img>
element – the <img>
element is always required!
Without any -x
descriptor, 1x
is assumed. Depending on browser, you may see that the 2× artwork gets used if it has been cached previously. When used in this way, the browser is forced to use certain images across certain breakpoints, but may still hold on to and use a higher-resolution image than needed.
Note that the src
specified for the <img>
tag will only ever be shown if none of the <source>
queries match. However, in these examples as the last <source>
tag specifies no media
attribute, it will always act as the fallback (if the others have not matched) for each image.
<picture>
<source media="(min-width: 70rem)"
srcset="img-1280.png">
<source media="(min-width: 50rem)"
srcset="img-960.png">
<source media="(min-width: 40rem)"
srcset="img-640.png">
<source srcset="img-480.png">
<img src="img-320.png">
</picture>
<picture>
<source media="(min-width: 70rem)"
srcset="img-1280.png 1x, img-1920.png 2x">
<source media="(min-width: 50rem)"
srcset="img-960.png 1x, img-1920.png 2x">
<source media="(min-width: 40rem)"
srcset="img-640.png 1x, img-1280.png 2x">
<source srcset="img-480.png 1x, img-960.png 2x">
<img src="img-320.png">
</picture>