Question

I was reading many questions on SO regarding best ways to detect screen size in pixels which is ultimately dependant on resolution to find the actual screen size.

I know some mobile devices have small screen (say 4inch) yet the resolution is high. While some devices r having large screen (say 7inch tab) yet the resolution is low.

So when you want to display your page to the user, you really need the screen size in inches or centimetres to give the best view comforting the eyes.

So I ask: Is there away to find out screen size of the device in inches not pixels ? I know it can be, provided that we know the resolution! !Bec we can calculate the size from screen width and height

Appreciating any idea!

Was it helpful?

Solution

once you have got the screen resolution in pixels, you can work out the dpi with a hidden div:

<div id="dpi" style="height: 1in; width: 1in; left: 100%; position: fixed; top: 100%;"></div>

js

var dpi_x = document.getElementById('dpi').offsetWidth;
var dpi_y = document.getElementById('dpi').offsetHeight;

then work out the resolution in inches:

var width = screen.width / dpi_x;
var height = screen.height / dpi_y;

Example

OTHER TIPS

Now, as far as I can tell there is no sure-fire way to accurately get the screen width of a device. Everything (including inches, 1in == 96px) is based in one way or another on screen resolution.

Now, I know this may not be the fix-all for everyone, but hopefully it helps a few people out there. It helped me, since I wanted my page to behave differently for mobile users, and my initial plan of attack was going to be based on screen size.

What I ended up doing was replacing the line

if (screen.height <= 768)

with

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))

As a disclaimer, I should also mention that this was from an answer that is a few years old now, so some devices may not be covered.

Source: https://stackoverflow.com/a/26577897/8082614

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top