I am trying to set up a <picture>
element with several child <source>
elements to serve images based on min-width and resolution conditions. I have 4 images:
- A wide 2x image (for retina devices with a min-width)
- A narrow 2x image (for retina devices under the min-width)
- A wide 1x image (for non-retina devices with a min-width)
- A narrow 1x image (for non-retina devices under the min-width)
Here's how I've put it all together:
<picture>
<source
srcset="Image_Wide_2x.jpeg"
media="
(min-width: 768px) and (-webkit-min-device-pixel-ratio: 2),
(min-width: 768px) and (min-resolution: 192dpi)" >
<source
srcset="Image_Narrow_2x.jpeg"
media="
(-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi)" >
<source
srcset="Image_Wide_1x.jpeg"
media="
(min-width: 768px)" >
<source
srcset="Image_Narrow_1x.jpeg" >
<img
src=“someFallbackImage.jpeg” >
</picture>
This works as expected, but the repeaded min-width query on the first source element bugs me. I tried:
<source
srcset="ImageA@2x.jpeg"
media="
(min-width: 768px) and (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)" >
But that the browser interpreted that as... "If both the min-width
and webkit-min-device-pixel-ratio
conditions are true, OR, just the min-resolution
condition is true"
When what I wanted was... "If the min-width
condition is true, and EITHER the webkit-min-device-pixel-ratio
or the min-resolution
condition is true"
I read the documentation for the media attribute here, but it isn't very clear (to me, at least) what the order of operations are when combining the logical OR and logical AND operators.
FYI - I got the suggested retina queries from here and here. I'm new to resolution queries, but I'm assuming I need both webkit-min-device-pixel-ratio
and min-resolution
, and that's what's tripping me up.
Is there a better way to achieve what I want, using the picture and source elements?