Serving Scaled Images in 2020

Serving Scaled Images with color splash

Serving an image on a website used to be as easy as using an <img> tag and maybe setting some basic style like width:100%. But with mobile phone, tablets, desktops, and even televisions being used to browse the internet, using one single image is often not the best development choice.

Why isn't one image the best choice?

The issue is that "one size doesn't fit all." Let's look at a piece of content from a website we recent developed for a local roofer. These four tiled images can be displayed three formats: 1 row of 4, 2 rows of 2, or 4 rows of 1. Each format is decided by the screen size the user is on, but the larger screen sizes do not require the largest images.

Four scaled images on four devices

So, how do we serve different images depending on the size of the screen?

The <picture> tag! Here is a basic example from the roofing website above:

<picture>
	<source media="(max-width: 736px)" srcset="/images/inspection_600.jpg">
	<source media="(max-width: 1280px)" srcset="/images/inspection_421.jpg">
	<img src="/images/inspection_272.jpg" class="tileImage" alt="Quality Roof Inspections" title="Man inspecting roof"/>
</picture>

Instead of using just an <img> tag we can use <picture> and <source> tags to give the browser more information about which photos to show. There are few things to note here -

  • The <img> tag is not optional and is the default image shown and will be the failover for old browsers that lack <picture> support.
  • The srcset attribute will replace the default src attribute within the <img> if the media conditions are met.
  • No matter which source is used, the class, alt, title, and other attributes of the <img> tag will always be used. There is no need to include these attibutes on the <source> tags.

Multiple Images

Of course, to make the code above work requires three images of various sizes saved for each of the four images on the page. This does take a bit of time and effort, but it ensures that the proper size image is being displayed and that the browser isn't downloading any more data than required.