A black and white photograph of a road disappearing into the distance

While illustrative images are now well-served in HTML5 and CSS with regards to high-DPI displays, with broad browser support for the picture element, srcset and sizes, Retina background images have been largely neglected during these advances. As background images are often quite large (in both pixel count and file size), this is particularly bothersome. While there has been an intermediate solution available for a long time, there’s now an even better one.

@media Solutions

A high-DPI image can be used on the appropriate screens using a @media query, as discussed in the previous article. Given an ordinary 72DPI image named automobile.jpg with a high-resolution version named automobile-2x.jpg, we can switch between the two being applied to the <body> with:

body {
    background-image: url("automobile.jpg");
    background-size: cover;
}

@media (-webkit-min-device-pixel-ratio: 2), 
(min-resolution: 192dpi) { 
    body {
        background-image: url("automobile-2x.jpg");
    }
}

image-set

A more concise and efficient method can be used with image-set. Because it is only currently supported in Webkit-derived browsers, it requires an approximate vendor prefix:

body {
    background-image: url("automobile.jpg");
    background-image: -webkit-image-set(url("automobile.jpg") 1x, url("automobile-2x.jpg") 2x );
    background-size: cover;
}

You might note that the syntax is very much like that for the x designator in srcset, used for ordinary responsive images.

Conclusion

image-set() is a promising method to use for Retina background images, but needs careful consideration: you can either use the now-traditional @media query to cover all browsers, or image-set() with a fallback, which will cover non-supporting browsers with a standard resolution image.

Photograph by Nadine Bauduin, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.