Product Designer & front-end Developer

Takes 2 min to read.

Responsive Background Images with image-set

Introduction

When we talk about responsive images, we tend to associate it with the HTML way of doing that, using srcset, sizes or the <picture> element. We were able to set different images in CSS using @media queries since forever, but the syntax was a bit cumbersome. However, CSS also has a less-known way of setting different images based on the screen resolution: The image-set() function.

The Problem

As technology evolve, devices are getting more and more complex, and programming languages need to adapt to accommodate for these new functionalities. Retina images were born to provide a comparable experience for those hiDPI devices, and in web development, we tend to associate them with the srcset and sizes HTML attributes, or the <picture> element.

However, we also had the ability to change images based on the device’s resolution on CSS for a long time, using CSS media queries:

/* For standard devices */
.rick {
background-image: url(images/rick-roll-400px.gif);
}

/* For hiDPI devices */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.rick {
background-image: url(images/rick-roll-800px.gif);
}
}

However, this syntax is (in my opinion) a bit cumbersome and hard to scale, especially as we’re getting 3x and 4x ppi devices. So how should this be handled? Embrace the image-set() function.

The Solution

The image-set() function allows you to specify multiple sources for the same image, on the same CSS declaration, similar to how srcset works:

.rick {
/* Fallback for older browsers */
background-image: url(images/rick-roll-400px.gif);
/* Prefixed version for Webkit browsers */
background-image:
-webkit-image-set(
url(images/rick-roll-400px.gif) 1x,
url(images/rick-roll-800px.gif) 2x,
);
background-image:
image-set(
url(images/rick-roll-400px.gif) 1x,
url(images/rick-roll-800px.gif) 2x,
);
}

With Firefox supporting this functionality in its upcoming release (the feature request for this implementation had been active lately) it’s, in my opinion, safe to use this technique over resolution media queries, with the corresponding background-image: url(...); fallback for older browsers.

Conclusion

That’s it for this post! Hopefully you learned a thing or two about how to progressively enhance the quality of your images based on the user’s device resolution, with this less known technique. Have fun with it!