Is there a srcset equivalent for css background image

image-set is the equivalent CSS feature. We should add equivalent srcset functionality (defining resources according to their dimensions) to the spec.

Currently implemented in all major Browsers (Firefox, Chrome, Safari, Edge) with the -webkit- prefix. Safari only supports supports the x descriptors.


Another approach, which is quite frankly more robust, would be to adapt the characteristics and options of background images to an image with the srcset attribute.

To do this, set the image to be width: 100%; height: 100%; and object-fit: cover or contain.

Here is an example:

.pseudo-background-img-container {
  position: relative;
  width:400px;
  height: 200px;
}
.pseudo-background-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="pseudo-background-img-container">

<img class="pseudo-background-img" src="https://cdn3.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep.jpg" srcset="https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep.jpg 640w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-280x175.jpg 280w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-432x270.jpg 432w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-216x135.jpg 216w" sizes="(max-width: 640px) 100vw, 640px">

</div>

This may not be the best approach for everyone but I imagine it will get most the desired results without any javascript workaround.


Pretty sure that:

background: -webkit-image-set( url('path/to/image') 1x, url('path/to/high-res-image') 2x );

works the same way. The browser will examine the images, see which fits best and will use that one.


For a polyfill, you can use an img with srcset as a mechanism for downloading the correct image size, then use JS to hide it and set the background-image of a parent element.

Here's a fiddle: http://jsbin.com/garetikubu/edit?html,output

The use of onload and putting the JS as a blocking script in the <head> is important. If you put the script later (say at the end of <body>), you can get a race condition where img.currentSrc hasn't been set yet by the browser. It's best to wait for it to be loaded.

The example allows you to see the original img being downloaded. You can easily hide it with some CSS.