Skip to content

Instantly share code, notes, and snippets.

@bergantine
Last active May 23, 2017 20:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bergantine/2114328 to your computer and use it in GitHub Desktop.
Save bergantine/2114328 to your computer and use it in GitHub Desktop.
CSS and JS to detect a retina display. #css #javascript #retina #responsive
<style>
/* from http://www.mobilexweb.com/blog/ios-5-1-new-ipad-web-developers */
@media screen and (-webkit-device-pixel-ratio: 2) {
/* retina display */
}
</style>
<script>
// from https://developer.mozilla.org/en/DOM/window.matchMedia
if (window.matchMedia("(-webkit-device-pixel-ratio: 2)").matches) {
/* retina display */
}
</script>
@guidobouman
Copy link

Actually, in JavaScript, window.devicePixelRatio is a safer alternative.
(See: http://caniuse.com/#feat=devicepixelratio vs. http://caniuse.com/#feat=css-media-resolution)

<script>
if (window.devicePixelRatio > 1) {
  /* highDPI display */
}
if (window.devicePixelRatio >= 2) {
  /* retina display */
}
</script>

@trainoasis
Copy link

But window.devicePixelRatio is not very reliable on mobile devices ?

@rdp
Copy link

rdp commented May 23, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment