Conditionally Display High Resolution Images in HTML/CSS for Retina Displays

2011.11.16 | iOS, Web Development | , , , , ,

Project 365 Day 175: Worth Queueing ForIt’s really easy to do but I tend to forget how to do it since it’s only applicable to mobile projects:

Let’s say you have: 200px by 100px image.png and the same image twice as large (400px by 200px) called image_highrez.png.

First, we can’t just use a plain ol’ <img> tag. We have to use the commonly done trick of creating a div with the same height/width as the image, then setting the background to the image. Anyone who’s used CSS sprite sheets should be very familiar with this process.

HTML:

<div id="our-image"></div>

CSS:

div#our-image {
  background-image: url(image.png);
  height: 100px;
  width: 200px;
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
  div#our-image {
    background-image: url(image_highrez.png);
    background-size: 200px 100px;
    -webkit-background-size: 200px 100px;
  }
}

Easy!

  • Luqman Shariffudin

    Thanks for the code. It works on my iPod Touch 4g.
    Have tested with my iPhone 3gs too for non-retina.