Detecting Retina Displays and Other High-DPI Screens
DPI,Retina
https://www.kirupa.com

If you are looking for a magical property that tells you what your current device DPI is, then you are in for some bad news. There is no such property. What we do have are ways of detecting when a particular DPI range has been hit. We do that using media queries and the min-resolution and min-device-pixel-ratio media features. There is just one more thing to cover. DPI values are represented as numbers. The higher the DPI, the more pixels are packed into a tiny part of the screen.


We'll talk more about them in a little bit, so don't worry if all of that sounds like gibberish. Now, with all that said, let's get to the markup and code.


The CSS Approach

In CSS, you can use a media query with the min-resolution feature to check for a Retina / high-dpi screen:

@media (min-resolution: 192dpi) {
   body {
     background-color: yellow;
   }
}

The value of 192 makes an appearance here. As mentioned in the introduction, a DPI value of 192 is a good minimum for designating a screen as being high-dpi (and Retina) capable. Looks like we are done, right? Well...


While this media query works for many users, the min-resolution media feature is still pretty new. To reach the most people, you need to also throw in the min-device-pixel-ratio media feature with a value of 2:

@media (-webkit-min-device-pixel-ratio: 2),
       (min-device-pixel-ratio: 2),
       (min-resolution: 192dpi) {
 
   body {
     background-color: yellow;
   }
}

The min-device-pixel-ratio media feature is deprecated by all the new browsers, so don't rely on it working for a very long time. Use it in addition to min-resolution to reach the most people, but don't use it just by itself.


The JavaScript Approach

You aren't limited to a CSS-only solution detecting whether you are running on a Retina/high-dpi screen. You can use the matchMedia method that lives on our window object to use our earlier media query approach in the world of JavaScript as well.


Take a look at the following snippet:

var query = "(-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi)";
 
if (matchMedia(query).matches) {
  // do high-dpi stuff
} else {
  // do non high-dpi stuff
}

The matchMedia method takes a media query as its argument, and the media query we are using is the exact one we used in our CSS approach earlier. If the media query evaluates to true, matchMedia returns true. Of course, if the media query evaluates to false, matchMedia returns a false as well.