3

I've been having trouble with my sizes attribute. I asked a question a while ago about which order you should declare sizes in and Yoav said:

"Your sizes value should start off at the narrowest breakpoint, and gradually move to the wider ones, so in your case it should be (min-width: 62.5em) 25vw, (min-width: 30em) 50vw, 100vw.

Otherwise, if you're on a retina screen, the screen's DPR is also taken into account when figuring out which image to pick."

This makes sense, but what happens in this situation. Say you have an image which is 100vw at mobile, but the container has max-width: 380px on it. I would do this:

sizes="(min-width: 380px) 380px, 100vw"

With me so far? Cool. At 700px the layout changes to two column, so you want the image to be 50vw. So I would do this:

sizes"(min-width: 700px) 50vw, (min-width: 380px) 380px, 100vw"

However, technically at min-width: 700px the image is now smaller than the min-width: 380px value, because 700 / 2 = 350px so should the order now be:

sizes"(min-width: 380px) 380px, (min-width: 700px) 50vw, 100vw" ?

Then at 1024px the layout changes to 3 column, and at 1200px the outer container stops the layout from expanding any more, so I want something like this:

sizes"(min-width: 1220px) 380px, (min-width: 1024px) 33vw, (min-width: 700px) 50vw, (min-width: 380px) 380px, 100vw"

Is this correct?

Community
  • 1
  • 1
patrickzdb
  • 928
  • 1
  • 10
  • 26
  • The thing is: the browser will use the first condition it finds true. So they're NOT cascading like regular css. The last condition will not be readed if it's not also the first it finds true. In other words, you must write the opposite of what you would do with regular css. – Luca Reghellin Aug 18 '17 at 10:52
  • @Stratboy if I write 1100w, 300w, 500w, 200w the order would not matter because the browser will use the first condition it finds true, is that right? – Alfrex92 Sep 05 '18 at 09:36

1 Answers1

6

The order depends on the media queries values and "direction" (min-width or max-width). The actual size of the image doesn't matter.

In your example:

sizes"(min-width: 380px) 380px, (min-width: 700px) 50vw, 100vw"

(min-width: 700px) 50vw will never be used, because the browser stops reading when it finds the first valid media query.

Here, with a viewport of 800px for example, min-width: 380px is true, so it stops there.

If you want to write more mobile first, try this (with max-width):

sizes"(max-width: 380px) 100vw, (max-width: 700px) 380px, 50vw"

It's counter intuitive because we write mobile first CSS with min-width media queries.

HTH

Nicolas Hoizey
  • 1,954
  • 1
  • 17
  • 24