Stop russian invasion of Ukraine 🇺🇦

Improving height behavior: 100VH on mobile

Improving height behavior: 100VH on mobile

Another pretty known issue is an ugly jumpy effect when you use 100VH points on mobile devices. As mobile browsers have a top address bar as a part of the UI, some space of your section will be cut or layout will be re-rendered and re-adjust since the dimensions have changed. Which is bad for user experience.

This issue was mentioned so many times in different articles and forums, but I would like to mention one where I take the solution from. Here’s the magic you’ll create:

As you can see, social icons get cropped at the bottom, but we want to see them without scrolling. Check out how it looks on mobile.

Just use a small chunk of JS and CSS to fix this—put the code into the heading of a page using Script and Style tags respectively.

JavaScript:


// First we get the viewport height and multiply it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);

When you scroll down, the address bar is collapsing which updates the value of --vh and repaints the page so the user may experience a jump effect.

In case of fixed height for the mobile landscape breakpoint, we don’t need the event listener as you can find in the original example:


// We listen to the resize event
window.addEventListener('resize', () => {
  // We execute the same script as before
  let vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
});

CSS:


/* We apply these styles only from the tablet breakpoint, desktop doesn't require it */
@media (max-width: 991px) {
  .hero {
    height: calc(var(--vh, 1vh) * 100);
  }
}
/* We set the fixed height for mobile landscape because there is not enough height space for the one screen section */
@media (max-width: 767px) {
  .hero {
    height: auto;
    min-height: 500px;
  }
}
/* And then again calculate the height for the hero section */
@media (max-width: 479px) {
  .hero {
     height: calc(var(--vh, 1vh) * 100);
  }
}

On a side note, updating the value of --vh will trigger a repaint of the page, and the user may experience a jump as a result. Because of this, I’m not advising you to use this trick for every projector to replace all usage of the vh unit, but only when you need your users to have an exact viewport unit value.

It might be interesting for you

Let’s create together

Start a project

Let’s create together

What are your interested in?

Budget

Timeframe

Personal details

Thank you for getting in touch!
We appreciate you contacting us.
We will get back to you shortly.
Dumka
Something went wrong while submitting the form.
Close