Reputation: 31
<img src="/images/photo-236x61.png" srcset="/images/photo-170x44.png 170w,
/images/photo-236x61.png 236w,
/images/photo-300x72.png 300w,
/images/photo-472x121.png 472w,
/images/photo-600x154.png 600w,
/images/photo-943x242.png 943w"
sizes="(min-width: 1341px) 450px,
(min-width: 1181px) 400px,
(min-width: 961px) 350px,
(min-width: 881px) 325px,
(min-width: 801px) 300px,
(min-width: 721px) 250px,
(min-width: 561px) 220px,
(min-width: 481px) 200px,
(min-width: 401px) 170px,
(min-width: 321px) 150px,
(min-width: 160px) 130px,
calc(100vw - 30px)" alt="My Photo">
I have the above image which as a fair number of different sizes based on how the designer wired things up. However, I'm running into weird issues where srscset always wants to pick much larger images than it needs to. For example, when the viewport is at 420px wide its picking the much larger 300px width image instead of the smaller ones that more closely match the srcset widths provided. Not sure why the queries aren't causing it to pick the correct sizes in different scenarios. Any one have any ideas how to know what the browser picks and why?
Upvotes: 2
Views: 3200
Reputation: 2603
srcset defines the list of images and what size each image is (the image's real size). This directive allows the browser to choose between them.
sizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true.
The order of sizes rule is important because the browser ignores everything after the first matching condition, so I think that the problem here should be the order.
When the viewport is at 420px wide, first sizes condition tells: "when the viewport width is 1341 pixels or more load the image referenced in the srcset list that most closely matches the chosen slot size (450px)".
The condition that is true is:
(min-width: 401px) 170px
The screen density is probably at least 2 (so 2 * 170px = 340px) so browser will choose srcset image: /images/photo-300x72.png 300w
that match the sizes condition.
Here is a useful article on how responsive images work.
Upvotes: 2