notes about srcset and images

Philipp Scheit
1 min readJun 28, 2022

--

The magic consists of two parts

a) the srcset, providing different image srces with their given width
b) the sizes attribute specifies how the image is rendered on which breakpoint

Imagine you are the browser and you want to load images.. do you know the size yet? — nope. You only see an url and you don’t have the meta data yet. That’s why we specify the srcset like thissrcset="<url> <image-width-in-px>w, ...” That is then the physical width of the image you have referenced via <url> in px.

Now imagine you have no clue about the custom css (yet) and how the image will be rendered. That’s why we write media queries in the <img sizes… attribute to specify: on the media width 640px the image is rendered with width x.

Cool things to know:

  • you need to order your media queries from biggest to lowest, cause only the first one will match (that makes sense, since the last and always matching condition comes after the last , without any media query)
  • you can use calc() in nearly all browser to do stuff like: calc(100vw — 10px) for an image that is full sized, but has a padding of 10px around it
  • srcset is supported by all browsers
  • you need to disable caching in chrome to get it working
  • chrome will never use a lower src from the set, if it has already loaded a bigger image (and can scale this down)
  • lighthouse uses 360px width

--

--