0

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?

Razzzzz
  • 21
  • 5
  • Possible duplicate of [Nesting Media Queries](https://stackoverflow.com/questions/16114000/nesting-media-queries) – jmcgriz Jun 19 '18 at 19:03
  • Nesting conditionals doesn't really work within media queries, you need to write out the entire statement each time in this case – jmcgriz Jun 19 '18 at 19:04
  • @jmcgriz Just to confirm, when you say "you need to write out the entire statement each time in this case", you mean that the way I have it written is correct? Or are you referring to a different way of writing it? – Razzzzz Jun 21 '18 at 17:34
  • Sorry, went on vacation - yes, the way you have it written is correct, there is no shorthand for combining media queries in the way that you'd like to. – jmcgriz Jul 05 '18 at 14:50
  • @jmcgriz Thanks! – Razzzzz Jul 11 '18 at 11:01

0 Answers0