If there's one thing that there've been an ample number of articles telling front end developers they must unequivocally adopt in the last five years, it's responsive images. We're all aware that more and more users are viewing our websites on mobile devices, and standard definition image assets simply won't do for today's retina displays. Thankfully, the W3C and WHATWG standards bodies have done a great job of taking feedback to give front-end developers simple but powerful tools to begin handling serving images at a wide range of resolutions for all the devices we now have to target. However, while eager web developers have been pushing everyone to add these new tools to their toolkit, recent projects have taught me that there are quite a few caveats that the considerate developer should be aware of before they start serving responsive images.

Firstly, let's discuss what tools currently exist and when to use them. The two main responsive image solutions added in HTML5 are img srcset and the <picture> tag. <picture> is a container for a set of image <source>s, where each source provides a srcset attribute with a path to the image you want to show and a media attribute with a standard media query breakpoint. You can list as many <source>s as you wish to have images, and each can also choose between a 1x or 2x size image for retina screens. Finally, there's a normal <img> tag at the end of your <source>s with all the standard src and alt attributes that you'd normally include. Regardless of what resolution you're viewing the page at, the <img> tag is actually the only rendered element, and all the <source>s do is swap out the src attribute in the <img> tag. Also, in the case that the browser doesn't support responsive images, the <img> tag is a safe fallback. If you're going to do any extra styling on your picture, just apply it to the <img> tag.

Subscribe to RSS - responsive design