I've been scouring responsive image posts and examples, but I can't find a solution. It seems like this should be easy, I might just be missing something: How would I serve the appropriate image size based on container width rather than screen width?
I.e. I have a desktop screen, 1980px wide, but a flex container that's 1/3 of the screen, so the max image size would only need to be 660px wide, so it should show the 800w image. But srcset will only go off of the screen size, so even if I'm displaying thumbnails, it will load the 1200w image. Is there a way to do this dynamically. i.e. still use flebox and dynamic widths, but have it serve the appropriate size based off of container width not screen width? Any help would be greatly appreciated, thanks!
<div class="flex justify-center w-1/3 mx-auto">
<img
srcset=" srcset="size-1.jpg 400w,
size-2.jpg 800w,
size-3.jpg 1200w,"
sizes=" (min-width: 1200px) 1200px, (min-width: 800px) 800px, 400px"
/></div>
You could mathematically describe how big the image would be displayed inside the sizes attribute. You can use calc() to achieve more complex calculation, for example if there is margin between your images and you want to be precise or if the container is not full width.
Example without calc():
<div class="flex justify-center w-1/3 mx-auto">
<img
srcset="size-1.jpg 400w,
size-2.jpg 800w,
size-3.jpg 1200w"
sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 33.33vw"
/>
</div>
Example with calc():
<div class="flex justify-center w-1/3 mx-auto">
<img
srcset="size-1.jpg 400w,
size-2.jpg 800w,
size-3.jpg 1200w"
sizes="(max-width: 600px) calc(100vw - 30px), (max-width: 1200px) calc(50vw - 30px), calc(33.33vw - 30px)"
/>
</div>