How to detect mobile browser for screen size?
Solution 1
You can use CSS:
@media screen and (max-width:500px) {
/* smaller screens */
}
@media screen and (max-width:960px) {
/* bigger screens */
}
Solution 2
You can get a wild approximation of the screen size with a bit of javascript
function getScreenSizeInches() {
var temp = document.createElement("div")
temp.style.overflow='hidden';
temp.style.visibility='hidden';
document.body.appendChild(temp)
temp.style.width = "10in"
var dpi = temp.offsetWidth / 10;
return screen.width / dpi + 'x' + screen.height / dpi;
}
See the following fiddles for its use in action vanillajs, or jquery..
jQuery version:
function getScreenSizeInches() {
var $temp = $('<div style="overflow:hidden;visibility:hidden;width:10in"/>').appendTo('body'),
dpi = $temp[0].offsetWidth / 10;
return screen.width / dpi + 'x' + screen.height / dpi;
}
As has been pointed out in the comments this technique can be wildly inaccurate so I wouldn't use it as anything other than a hint toward screen size...
Solution 3
You could use CSS:
/*Here goes the CSS for all screens*/
@media handheld {
/*Here goes the CSS for mobile phones and tablets*/
}
EDIT:
Another suggestion:
set the viewport
metatag in your html:
<meta name="viewport" content="width=device-width, height=device-height" />
now you can get the dimensions like this: Get the browser viewport dimensions with JavaScript
Esaevian
Updated on July 09, 2022Comments
-
Esaevian almost 2 years
I'm working on a site that needs to work on desktop and mobile. Right now I have a main content div that is set to 70% of the screen width. However, I feel that this is to small for mobile devices (like phones, not so much tablets) and want to up it to 90 or 95% How can I do this (say for screen sizes smaller than 5 inches) without using terribly unreliable browser sniffing? I hear the mantra "feature detection feature detection feature detection" over and over, and I understand why that's a good thing...but I don't know what "feature" to detect for this problem...
Thanks.