Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Srcset with multiple min-width vw and px values, which wins and why?

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?

like image 909
patrickzdb Avatar asked Nov 20 '25 08:11

patrickzdb


1 Answers

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

like image 168
Nicolas Hoizey Avatar answered Nov 22 '25 23:11

Nicolas Hoizey