What is the right way to calculate how much viewable space is available on mobile Safari? By viewing area, we mean the amount of the screen actually available to a web app,
Set the CSS height
of your root container element (let's call it rootElement
) to the height of the view port:
.root-element {
height: 100vh;
}
Then, when the page did render, run this code to update rootElement
height to the view port height minus the size of the browser UI bars (for example, on iOS Safari: top address bar, bottom navigation bar…):
const rootElement = document.querySelector(".root-element")
const viewPortH = rootElement.getBoundingClientRect().height;
const windowH = window.innerHeight;
const browserUiBarsH = viewPortH - windowH;
rootElement.style.height = `calc(100vh - ${browserUiBarsH}px)`;
This solution sets the size of your root container to what is available, but it also keep the possibility for the browser to adapt rootElement
height when the window is resized (when used on a desktop, for instance).
window.innerWidth
and window.innerHeight
will give the width and height of the viewport.
I know this is 5 years old post, but this problem still persists as i can tell. My workaround:
Use a HTML Element on the page which is styled with CSS: .el{ height:100vh; }
and retrieve the height in pixel to Javascript by using jQuery: $('.el').height();
If you don't have a practical use for such a element you might create one on the fly for the sole purpose of masuring the viewport:
var vh = $('<div style="height:100vh"></div>"').appendTo('body').height();
$('body div:last-child').remove();
For anyone who comes in 2020, window.screen.availHeight
is the only one that works as @Marcel Falliere
's comment below.