Don't use 100vh for mobile responsive

Don't use 100vh for mobile responsive

ยท

2 min read

Generally, we use height:100vh for fullscreen layout which is an easy hack and convenient way to get better design.

Example

.content {
   height: 100vh;
}

But when we test our design on an actual device, we encounter several issues:

  • Mostly Chrome and Firefox browsers on mobile have got a UI (address bar etc) at the top.

  • On Safari it gets more tricky address bar is at the bottom.

  • Different browsers have differently sized viewports

  • Mobile devices calc browser viewport as (top bar + document + bottom bar) = 100vh

  • The whole document is filled to the page using 100vh


Problems

  • On Chrome

Chrome 100vh issue

Scrollbar issues have been detected. Bad user flow and difficulty to navigate the content.

Note: I have also tested these issues on safari which makes more bad user flow


Solutions

Detect the height of the app by using JS

Setting the height of the page (using javascript) with the window.innerheight property.

const documentHeight = () => {
 const doc = document.documentElement
 doc.style.setProperty('--doc-height', `${window.innerHeight}px`)
}
window.addEventListener(โ€˜resizeโ€™, documentHeight)
documentHeight()

Using, CSS Variable

:root {
 --doc-height: 100%;
}

html,
body {
 padding: 0;
 margin: 0;
 height: 100vh; /* fallback for Js load */
 height: var(--doc-height);
}

Here, the documentHeight function sets new style property var('--doc-height') and includes the current window height.


Final Results

Chrome Browser

CSS 100vh viewport

Note: There is no vertical extra scrollbar appearing now also no issues on Safari too. The bottom address bar of safari is always on the bottom which makes good user flow to the website


Conclusion ๐Ÿ‘๐Ÿ‘ By coming this far I hope you can solve the mobile devices' viewport issues. So, I suggest you give your a try on your project and enjoy it!

Feel free to share your thoughts and opinions and leave me a comment if you have any problems or questions.

Till then, Keep on Hacking, Cheers

ย