For each post on a website, there will be a header image. This image will have a width of 100vw
and a height of 300px
. I would like to deliver multiple versions of this image via either the srcset
attribute of an img
tag or a full-fledged picture
element (not sure which at this point, hence this question).
Doing so would be rather easy using the srcset
attribute:
<img srcset="lg.jpg 1200w, md.jpg 992w, sm.jpg 768w, xs.jpg 320w" sizes="100vw" src="xs.jpg">
The problem arises when I want to account for different device pixel ratios. First, assume I have 2x
and 3x
versions of all of the images listed in the srcset
above.
Let's say I have a 2x
phone with a 320px
-wide viewport (e.g. an iPhone 5). I'd want the browser to load xs_2x.jpg
. Likewise, let's say I have a 1x
desktop with a widescreen monitor. I'd want the browser to load lg.jpg
.
But now let's say I have a larger phone, one with a 3x
, 414px
-wide viewport (i.e. an iPhone 6 Plus). In this case, I'd want my browser to load sm_3x.jpg
. But, my browser would likely load sm_2x.jpg
instead because the width of sm_2x.jpg
(1536 pixels) is closer to the width of the phone (1242 pixels) than the width of sm_3x.jpg
(2304 pixels). This would result in an image that is not 300px
tall on the device, breaking a requirement of the website.
How can I implement dynamic-width, static-height, DPR-conscious responsive images?