100vh solution for mobile

100vh solution for mobile

Tomoya's photo
ยทOct 16, 2021ยท

2 min read

Do you know that 100vh on mobile is tricky? On mobile, the 100vh includes an address bar, therefore the height does not correspond to the real viewport.

Here are more details if you are not familiar with this topic.

These solutions above have some drawbacks. Setting vh css variable isn't great because it doesn't support resizing. For this, we could add an event listener, but it would result in a repaint. Also, on desktop, -webkit-fill-available does not work correctly.

So, here is my solution for 100vh.

        vh100 = document.createElement("div"); = "100vh"
        document.body.appendChild(vh100);"--address-bar-height", vh100.clientHeight - window.innerHeight);

I started by creating an element with a height of 100vh, then subtracted the 100vh using window.innerHeight to set the address-bar-height css variable. This works on both desktop and mobile devices. Also, because the css variable is undefined until this script is loaded, you should place this JavaScript directly below body tag.

And in css, we can use it as below.

.vh-100 {
    height: calc(100vh - var(--address-bar-height) * 1px);

Please multiply the amount by 1px because --address-bar-height is a numeric value that does not include the px unit.

Here is my demo.

Enjoy my approach ๐Ÿ˜€

Share this