I'm in the process of trying to wrap my head around using srcset
and sizes
on img
tags.
Whilst I think I have grasped the basics – mainly thanks to this article – I'm struggling in practical application of the sizes
attribute.
In all the examples I can find, things are massively simplified and the sizes attribute is declared as if at each breakpoint, the image width will be an exact proportion of the viewport width, allowing the use of vm
units. For example:
sizes="(min-width: 36rem) 33.3vw,
100vw"
Of course in real life, images are often within other containers which themselves might be within other containers and so on, each with their own margin, padding or positioning.
Is it fair to say that in all but the simplest cases (when images are of fluid width and are not simply an exact percentage of the viewport), calc
must be used, potentially adding hideously complex calculations to the html markup as an images dimensions need to be calculated working from viewport width, down through any containers to the image? For example how would you calculate the correct size for an image located a container with 7px padding that is itself inside a container that is 45% of its container with 15px margin that is inside a sidebar that is 25% of the main page container which has 15px of padding and has a min-width of 1220px?
sizes="(min-width: 36rem) calc(((((1220px - (2 * 15px) * 25%) * 45%) - (2 * 15px) - (2 * 7px)),
100vw"
Trying to calculate this in the sizes attribute seems ludicrous, especially given that all this might change at each breakpoint. having to keep this massively complex calculation in sync with changes to the CSS seems like madness. And then you have the patchy browser support for calc
.
I feel like I'm missing something obvious, but what is it?
Note: I'm aware of Alexander Farkas's excellent Lazy Sizes which does the size calculations for you through the use of data
attributes, but I'm interested in standard usage.