Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS for high-resolution images on mobile and retina displays

My website images look blurry for users with retina displays. (For example, on the Retina MacBook Pro).

How do I serve high-resolution images to visitors with retina displays, but standard-sized images to everyone else, while keeping the image the same apparent size?

like image 890
Chris Nolet Avatar asked Jun 16 '12 03:06

Chris Nolet


People also ask

What should you resize the image to if your users are using retina displays?

To accommodate high resolution/retina displays, you'll want to use an image that's 1280 pixels wide, which is what's referred to as “2x”. While the graphic will still display on the website at 640 pixels wide, you are doubling the pixel density by using an image that's double the size.

What is retina display CSS?

Pixel density refers to how many pixels are contained within a space, usually measured by pixels per inch, or PPI for short, and sometimes referred to as dots per inch, DPI. Retina displays have double the number of pixels per inch and can fit two pixels within the same width and height of a non-Retina display.


1 Answers

In your HTML, create a <div> like so:

<div class="ninjas-image"></div>

And in your CSS, add:

.ninjas-image {
  background-image: url('ninja-devices.png');
  width: 410px;
  height: 450px;
}

@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
  .ninjas-image {
    background-image: url('[email protected]');
    background-size: 410px 450px;
  }
}

The magic here is in the CSS @media query. We have a double-sized image ([email protected]) that we sub-in when the device reports a ‘device pixel ratio’ of 1.5 (144 dpi) or more. Doing it this way allows you to save on bandwidth by delivering the original, smaller image to non-retina devices, and of course it looks great on retina devices.

Note:

This answer was updated in 2016 to reflect best-practice. min-device-pixel-ratio did not make it in to the standard. Instead, min-resolution was added to the standard, but desktop and mobile Safari don't support it at the time of writing, (thus the -webkit-min-device-pixel-ratio fallback). You can check the latest information at: http://caniuse.com/#feat=css-media-resolution.

like image 198
Chris Nolet Avatar answered Sep 30 '22 16:09

Chris Nolet