Start Using SRCSET IMG Attribute For Serving Device Specific Images

The article, JavaScript Low Resolution Image Replacer, discussed a JavaScript solution for replacing low resolution images with higher resolution ones after the page finishes loading all the initial resources (thereby reducing the load time of your pages). But what about loading different image sizes based on the resolution of the user’s device. We could write a JavaScript solution for this (and some developers have), but HTML 5 already introduces the concept of <img srcset[2] to serve different images for different resolutions.

How do it…

Here is how to use srcset by specifying image widths:

<img src="<pathToImages>/image-small.png"
     srcset="<pathToImages>/image-medium.png 500w, <pathToImages>/image-large.png 1000w"
     alt="my image">

Here is how to use srcset by specifying pixel density (eg. non-retina == 1x):

<img src="<pathToImages>/image-normalRez.png"
     srcset="<pathToImages>/image-highRez.png 2x"
     alt="my image">

Both pixel density and pixel width can also be specified for srcset (the large image will only be shown on retina devices):

<img src="<pathToImages>/image-small.png"
     srcset="<pathToImages>/image-medium.png 500w, <pathToImages>/image-large.png 1000w 2x"
     alt="my image">

How it works…

In srcset, define any number of comma separated image URLs, each followed by a pixel width (w) descriptor and/or a pixel density (x) descriptor. If you don’t provide a width, the browser will assume infinity, and if you don’t provide a pixel density, then the browser will assume 1x. The browser uses the pixel density descriptor to determine if the image should be shown to the current device, and then calculates the best size image using pixel width descriptor. For example, assuming we have three images each twice as large as the previous (500, 1000, 2000) and a device with a 320 pixel screen width and 1x pixel density, then the following calculations are made[1]:

500 / 320 = 1.5625
1000 / 320 = 3.125
2000 / 320 = 6.25

The closest value larger than 1 (1x) is 1.5625, so the browser will use the smallest image. But, increasing the pixel density of the device to 2x (eg. a retina device) will cause the browser to use 3.125 for the same reason: 3.125 is the closest value larger than 2 (2x).

As you can imagine, like many HTML 5 features, this attribute probably doesn’t work on the browser that visitors to your site are using[3]. Fortunately, there is a good polyfill[4] to enable the feature in legacy browsers, so there is little reason not to begin using srcset today.


  1. Responsive Images: If you’re just changing resolutions, use srcset
  2. MDN: IMG Attribute SRCSET
  3. Can I use SRCSET
  4. Picture Fill - Image Polyfill