Crashalot
Crashalot

Reputation: 34523

How to calculate height of viewable area (i.e., window height minus address & bookmark bars) in mobile Safari for web app?

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, that is the window height minus the address and bookmark bars.

iOS 7 prevents hiding of the address bar, and we need to properly account for the viewport height.

Upvotes: 30

Views: 41701

Answers (4)

MonsieurDart
MonsieurDart

Reputation: 6045

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 renders, run this code to update rootElement height to the viewport 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).

Upvotes: 4

Luu Hoang Bac
Luu Hoang Bac

Reputation: 442

For anyone who comes in 2020, window.screen.availHeight is the only one that works as @Marcel Falliere's comment below.

Upvotes: 9

23b
23b

Reputation: 68

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();

Upvotes: 1

neilco
neilco

Reputation: 8012

window.innerWidth and window.innerHeight will give the width and height of the viewport.

Upvotes: 24

Related Questions