Detecting Physical Screen Dimensions Of Webkit Devices In Javascript
Solution 1:
There's no direct way to get the screen size in inches, but there are workarounds that use screen density to find the device size. It's not perfect, but you don't really need to know the exact size to 5 significant figures. Also, it is normally better to simply use pixel values, IMO.
HTML
Make a test div, and then see the number of pixels displayed to get the pixel density, then use that in your calculations. This should work, assuming that your browser/OS are configured properly (it didn't work in the this question but it was within half an inch on my computer).
EDIT: This is 100% wrong. The inch/cm measurements in CSS aren't based on an actual physical measurement. They're based on an exact conversion (1 inch = 96 px, 1 cm = 37.8 px). My apologies.
CSS
The best way to detect physical screen size is to use CSS media queries. The min-resolution
and max-resolution
queries can be used to get the resolution in either dpi
or dpcm
:
@media (min-resolution: 300dpi){
// styles
}
Combining it with the min-device-width
and max-device-width
queries, you get something like:
@media (resolution: 326dpi) and (device-width: 640) and (device-height: 960){
// iPhone
}
The problem is that if you want to target 7 inch devices, you'd have to have many resolutions and corresponding widths that go together, which could get complicated.
For more information:
- MDN- CSS Media Queries
- MDN- Resolution
- "Mobifying" Guide
- High DPI Images for Variable Pixel Densities (Somewhat Related)
Javascript
You can use window.devicePixelRatio
to determine the screen density. From Android's WebView Reference:
The
window.devicePixelRatio
DOM property. The value of this property specifies the default scaling factor used for the current device. For example, if the value ofwindow.devicePixelRatio
is "1.0", then the device is considered a medium density (mdpi) device and default scaling is not applied to the web page; if the value is "1.5", then the device is considered a high density device (hdpi) and the page content is scaled 1.5x; if the value is "0.75", then the device is considered a low density device (ldpi) and the content is scaled 0.75x.
Then using this, you calculate the physical size by dividing this by the total number of pixels, which can be calculated with window.screen.width
and window.screen.height
(Don't use window.screen.availHeight
or window.screen.availWidth
because these only detect the available height).
For more information:
Solution 2:
better to use CSS
@media screen and (max-width: 672px){
//your code for mobile category
}
@media screen and (min-width: 672px){
//your code for desktop category
}
Post a Comment for "Detecting Physical Screen Dimensions Of Webkit Devices In Javascript"