One of the biggest challenge of responsive web design are images. In the quest of delivering crisp images web designers and developers have increased the size of data being transferred for images. Since images attribute to 60% of the bandwidth used to optimize the user experience it is important to have the ability to show different image sizes on different devices. Images are one of the biggest obstacles in implementing truly responsive web design. Different solutions have been suggested to overcome the problem of implementing responsive images in web design. One of the solution, using srcset attribute, was discussed in a earlier post.
Another solution is the picture HTML5 tag (<picture>) which was part of the HTML5 specification. Finally browsers are implementing support for the picture tag and it’s implementation is being recommended though with caution. In fact using srcset attribute with picture tag is ideal to ensure that appropriate images are displayed by different devices depending on the device’s screen size and device pixel ratio.
Purpose of the picture element
The picture element is a container which provides multiples sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors.Whatwg
What this means is that inside the picture element there are set of source tags. Each source tag has a set of rules and the image to use in case the set of rules are true. An image tag is also needed as a fall back in case a browser does not support the picture tag. The browser reads the rules and as soon as a set of rules is matched the matching image is displayed. If none of the rules match then the image specified in the img tag is shown.
The process of displaying different images based on device characteristics is called art direction. The picture HTML5 tag helps in implementing art direction.
Example of picture HTML5 tag
<picture> <source media="(min-width: 800px)" srcset="head.jpg, head-2x.jpg 2x"> <source media="(min-width: 450px)" srcset="head-small.jpg. head-small-2x.jpg 2x"> <img src="head-fb.jpg" srcset="head-fb-2x.jpg 2x"> </picture>
In the above example if the screen width is at least 800 pixels either head.jpg or head-2x.jpg is shown depending on the device-pixel-ratio. If the screen width is between 450 and 800 pixels then either head-small.jpg or head-small-2x.jpg is shown depending on the device-pixel-ratio. If the screen size of the device does not match either criteria then the head-fb.jpg or head-fb-2x.jpg is shown depending on the device-pixel-ratio.
Using this method images are truly responsive because this method checks for both the screen width and device-pixel-ratio to determine the image that has to be rendered.