Following along from my recent post about responsive images using pure HTML, this post is about the more server-centric option. It doesn’t answer the art direction question, but it can help reduce the amount of HTML required to implement fully responsive images.
If you are aware of responsive images and the
<picture> element, you’ll know that the code required to give the browser enough choices and information in order to have it request the correct image can be somewhat verbose.
This article will cover the other side of the story, allowing the server to help with the decision of which image to show and ultimately greatly reducing the HTML required to achieve responsive images
srcset, sizes, and picture element
The term “Responsive Images” has been in common use for a while now. It refers to the ability to deliver the most appropriate image for the available viewport size, pixel density, even network connectivity.
For example, a Mac with a huge retina display is capable of displaying an extremely high resolution, large, image; whereas a phone in portrait mode on 3G may be better off with a smaller image – both in terms of dimensions and file size – which has been cropped to focus on the most important part of the image.
To achieve this required a significant amount of effort from the Responsive Images Working Group (RIWG) to help get functionality like the
<picture> element and support for
sizes attributes on both
<img /> into major browsers.
The srcset attribute allows us to define different sources for the same image, depending on the size and pixel density of the device’s display.
srcset’s “x” – pixel density (dpr)
So to display a different image for different pixel densities (e.g. standard definition or high def/retina) we might use something like:
img-3x.png 3x" />
The browser then decides which image to request based on the device capabilities (and potentially connectivity too).