Search code examples
cssangularheightviewport

viewport height (100vh) on mobile leads to unwanted scroll


I'm developing a theme for mobile in Angular 10.

And I've used vh to set height of components.

My app is pretty much complex and I've set height in vh in 100s of places. Altering every height to px's or % isn't possible for me.

I'm fully aware that this issue isn't new and there are many solutions available on different forums. But none worked for me.

I used following script. But I got error --vh is undefined.

<script>
     window.addEventListener('resize', () => {
      // We execute the same script as before
      let vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    });
  </script>
  <style>
    body {
      height: calc(var(--vh, 1vh) * 100);
    }
  </style>

Even if somehow I manage to make it work I got to alter it in many places which isn't possible for me.

Any suggestion will be appreciated.

Thanks.


Solution

  • A couple of things.

    First the code to set the CSS variable --vh. It needs to be run on the initial and any subsequent load as well as on resize:

    function resize() {
      // We execute the same script as before
      let vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    }
    
    window.addEventListener('resize', resize);
    window.addEventListener('load', resize);
    body {
      height: calc(var(--vh, 1vh) * 100);
    }
    <body>
    </body>

    Second, altering the use of vh to --vh.

    I guess you'll need to set up an edit macro, or just set up a find and replace and go to next by hand as you'll probably want to check you have the substitutions right.

    e.g. for 80vh you'll want calc(var(--vh) * 80); Actually, I've done it on a project and it wasn't too bad, but I didn't have hundreds which you mention. Luckily vh is an unusual string so not too hard to find the next one.