High resolution web images on high dpi displays

Wouter ten Brink
Elements blog
Published in
2 min readFeb 13, 2015

As products with a higher pixel density displays (marketed by Apple as “Retina Displays”) become more popular, it becomes more useful to provide (bitmap) images on webpages in higher resolutions to ensure a better user experience.

Of course you could achieve this by simply replacing all low resolution images by high resolution counterparts while maintaining the original pixel dimensions. The downside is that low resolution devices would still be required to download the high resolution images which are often larger in file size and thus slowing down the page load.

HTML5 introduced the nifty “<picture>” tag and the “srcset” attribute for the “<img>” tag, which address this issue. Unfortunately not all major browsers support these yet (or have them switched off by default, I’m looking at you, Firefox).

A pure CSS approach that works in all major browsers is by using CSS3’s @media query. Using @media you can define different styles for different media types, traditionally used for providing an alternative style sheet for the printed version of a webpage.

The trick is to provide the “min-resolution” condition to see whether the display support a certain resolution. Note that some browsers, such as Safari, support the older, non-standard “device-pixel-ratio” media query, so it is smart to include this too to support all popular browsers.

The following sample shows a logo image of 256×256 pixels on low resolution displays and shows a 512×512 pixels alternative in the same space for 144dpi or higher (pixel ratio of 1.5) displays.

<style type="text/css">
#logo {
background-image:url('logo@1x.png');
width:256px;
height:256px;
background-repeat:no-repeat;
background-size:256px 256px;
}
@media print, only screen and (-webkit-min-device-pixel-ratio: 1.5), screen and (min-resolution: 144dpi), screen and (min-resolution: 144dppx) {
#logo {
background-image:url('logo@2x.png')
}
}
</style>
<div id="logo"></div>

Don’t forget to set the background image size to the original dimensions using the CSS3 “background-size” property or only the top left quarter of the image is displayed.

Originally published at www.elements.nl on February 13, 2015.

--

--

Wouter ten Brink
Elements blog

WonderBit co-founder. Tech enthusiast. Lives for thinking up and delivering digital solutions to fix real-world problems.