Fix mobile viewport 100vh bug in one line of CSS: Dynamic viewport units in action

Use DVH instead of VH as a more complete unit

Oleksandr Shevchuk
3 min readMar 28, 2023
Image by Freepik

Do you know about the strange mobile viewport bug, also called the 100vh bug? Or how to create a fullscreen block in the right way? In this article, I’m going to explain the nature of this bug and the better way to fix it.

What is the mobile viewport bug?

Have you ever created a fullscreen element on your webpage? It is not hard to do just adding one line of CSS:

.my-element {
height: 100vh
}

The 1vh takes 1% of the viewport height, exactly what we need. But when we test on mobile devices, something wrong happens. The mobile browser's viewport can be changed dynamically, but the vh value remains unchanged. So in mobile browsers vh becomes a static value and doesn’t reflect the actual height of the viewport.

In the illustration below you can see two states of the mobile screen:

  • With a hidden address bar
  • With a visible address bar

For both of these states, 100vh has the same value and as a result, the CTA button comes outside the first screen. It creates problems:

Mobile 100vh bug
Original image from Stack Overflow

The regular fix

The solution I’ve used before involved using CSS Custom Properties and some Javascript. In short words, we listen to the resize event and set the --vh custom property (1% of window height) every time the window size changed:

Codepen presentation for https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

For a better understanding, please look at this awesome CSS-Tricks article:

The better way

According to CSS Values 4 Specification: Viewport-relative lengths we can use new viewport units. There is a dvh unit that does the whole job. It always adapts itself to the viewport size. And finally, the browser support is perfect:

Small, Large, and Dynamic viewport units browser support sreenshot
Small, Large, and Dynamic viewport units browser support

With this cool feature, the solution becomes pretty simple, you need only one line of CSS:

.my-element {
height: 100dvh
}

Read more about new other amazing dynamic viewport units:

Conclusion

Nowadays, CSS is growing fast and helps so much in solving front-end problems. The dvh unit is the best choice for making the viewport-dependent height. It’s a really simple and powerful CSS feature, that makes your job easier. Furthermore, it is supported in all major browsers, so you can use it now.

🎉 UPD: Recently I found that dvh the unit is already used in Vuetify 3, the component framework for Vue.js. If you know other projects, where it’s used, please share in the comments, and let other people know about it!

🙏 Hope that you just read an interesting and helpful story.

👏 If you like it just send a clap, I’ll be very excited to see your reaction!

👆Follow me to be the first who will see my new articles.

Thanks and BR Oleksandr

--

--