I have 3 different layouts for a design I completed in Sketch. Each design has a header image as can be seen below:
On different devices, I load a different image to keep the height in check and crop the image. When I export from Sketch I have the following images:
dog-header-mobile-1x.png
dog-header-mobile-2x.png
dog-header-mobile-3x.png
dog-header-mobile-4x.png
dog-header-tablet-1x.png
dog-header-tablet-2x.png
dog-header-tablet-3x.png
dog-header-tablet-4x.png
dog-header-desktop-1x.png
dog-header-desktop-2x.png
dog-header-desktop-3x.png
dog-header-desktop-4x.png
I'd like to load the 1x, 2x, 3x and 4x images where appropriate. But what's confusing me is I have 3 different images for the 3 devices so do I need to use srcset
AND sizes
to achieve this? It seems like a very long-winded way to do this and I'm pretty sure I'm doing it wrong.
You can use the <picture>
element.
<picture>
<source
media="(max-width: 740px)"
srcset="
dog-header-mobile-1x.png,
dog-header-mobile-2x.png 2x,
dog-header-mobile-3x.png 3x,
dog-header-mobile-4x.png 4x">
<source
media="(max-width: 1440px)"
srcset="
dog-header-tablet-1x.png,
dog-header-tablet-2x.png 2x,
dog-header-tablet-3x.png 3x,
dog-header-tablet-4x.png 4x">
<source
srcset="
dog-header-desktop-1x.png,
dog-header-desktop-2x.png 2x,
dog-header-desktop-3x.png 3x,
dog-header-desktop-4x.png 4x">
<img src="dog-header-desktop-1x.png" alt="Dog">
</picture>
IE doesn't support it, but will fallback to the default img
element.