I am trying to understand the basics of responsive images.
I have this very simple webpage:
http://chubby-orange-fox.s3-website.eu-north-1.amazonaws.com/test.html
<!DOCTYPE html>
<head>
<title>Responsive</title>
</head>
<html>
<body>
<img srcset="https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.1&w=2000 200w,
https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.2&w=2000 400w,
https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.4&w=2000 800w,
https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.6&w=2000 1200w,
https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.8&w=2000 1600w,
https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=1&w=2000 2000w" title="test image" alt="test image" aria-label="test image" width="350" height="197" loading="lazy">
</body>
</html>
As you can see, the srcset
contains 6 different images and they have the sizes 200w
(200px), 400w
(400px), 800w
(800px), 1200w
(1200px), 1600w
(1600px) and 2000w
(2000px).
However, as you can see, I have explicitly also added width="350px"
on the <img>
tag, Chrome knows the image will be displayed with a width of 350px.
So if Chrome acknowledge that the image will be rendered with a width of 350px:
Why is it picking the https://www.datocms-assets.com/58071/1637680873-dadandchildbywindow-edited.png?auto=format&dpr=0.6&w=2000 1200w
version that is 1200px
large, when there is clearly a 400w
(400px) version that is more suited?
2
Answers
In these responsive times,
width="350" height="197"
is now more used by the browser to know the image width/height ratio than the actual rendered dimensions in CSS pixels.With
w
descriptors insrcset
, the browser needs asizes
attribute to know which is the target rendered width. Ifsizes
is missing, the fallback value is100vh
, the full viewport width.If you really want a fixed rendered image width, you should:
sizes
with said fixed width in CSS pixelsx
descriptors instead ofw
descriptors insrcset
I have also been struggling with this problem where I got the biggest image. I ended up converting the image to 16:9 ratio, the same as the display ratio. This resulted in showing a smaller
srcset
version than the old ratio (500∶243).I also had a issue with the image being quite pixelated, probably because it was a big image compressed into a small element. This issue went away after changing the ratio and getting a smaller resolution. Later I found an explanation here:
object-fit : cover gives pixelated images on chrome