100vh solution for mobile

100vh solution for mobile

ยท

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.

<body>
    <script>
        vh100 = document.createElement("div");
        vh100.style.height = "100vh"
        document.body.appendChild(vh100);
        document.documentElement.style.setProperty("--address-bar-height", vh100.clientHeight - window.innerHeight);
        vh100.remove()
    </script>
    <div>contents...</div>
</body>

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.

<style>
.vh-100 {
    height: calc(100vh - var(--address-bar-height) * 1px);
}
</style>

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 ๐Ÿ˜€