Skip to content

Instantly share code, notes, and snippets.

@nhoizey
Last active May 28, 2021 15:31
Show Gist options
  • Save nhoizey/a993b1f8e0263bd2ef83e78a4378bbb1 to your computer and use it in GitHub Desktop.
Save nhoizey/a993b1f8e0263bd2ef83e78a4378bbb1 to your computer and use it in GitHub Desktop.
Get screen density and viewport width, useful for responsive web design
// get device pixel ratio in dppx
// https://github.com/ryanve/res/blob/master/res.js
var screen_density =
typeof window == 'undefined'
? 0
: +window.devicePixelRatio ||
Math.sqrt(screen.deviceXDPI * screen.deviceYDPI) / 96 ||
0
// keep only 3 decimals: http://jsfiddle.net/AsRqx/
screen_density = +(Math.round(screen_density + 'e+3') + 'e-3')
// get viewport width
// http://stackoverflow.com/a/8876069/717195
var viewport_width = Math.max(
document.documentElement.clientWidth,
window.innerWidth || 0,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment