0
0
CssDebug / FixBeginner · 4 min read

Fix 100vh Issue on Mobile in CSS: Simple Solutions

The 100vh unit on mobile browsers includes the browser's address bar, causing layout issues. To fix this, use JavaScript to set a CSS variable with the actual viewport height and use that variable instead of 100vh in your CSS.
🔍

Why This Happens

On mobile browsers, 100vh measures the full height including the browser's address bar and UI. When the address bar hides on scroll, the visible area changes but 100vh stays the same, causing content to overflow or have extra space.

css
html, body {
  height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.main {
  height: 100vh;
  background-color: coral;
}
Output
The coral box covers the full screen height including the browser UI, causing vertical scroll or blank space when the address bar hides.
🔧

The Fix

Use JavaScript to get the actual viewport height and set it as a CSS variable. Then use that variable for height instead of 100vh. This updates on resize and avoids layout issues.

css and javascript
/* CSS */
html, body {
  margin: 0;
  height: 100%;
}

.main {
  height: calc(var(--vh, 1vh) * 100);
  background-color: coral;
}

/* JavaScript */
function setVh() {
  const vh = window.innerHeight * 0.01;
  document.documentElement.style.setProperty('--vh', `${vh}px`);
}

window.addEventListener('resize', setVh);
window.addEventListener('load', setVh);
Output
The coral box fills the visible viewport height exactly, adjusting when the browser UI shows or hides, with no extra scroll or blank space.
🛡️

Prevention

Always avoid using raw 100vh on mobile for full-height layouts. Instead, use the CSS variable method with JavaScript to handle viewport changes. Test on real devices and use browser DevTools mobile mode to check behavior.

Keep your JavaScript minimal and debounce resize events if needed for performance.

⚠️

Related Errors

  • Content cut off under fixed headers: Happens when fixed elements overlap content due to incorrect height calculations.
  • Scroll jumps on orientation change: Caused by viewport height recalculations not handled properly.
  • 100vh causing vertical scroll: Often due to browser UI height included in 100vh.

Key Takeaways

100vh includes mobile browser UI height, causing layout issues.
Use JavaScript to set a CSS variable with actual viewport height.
Replace 100vh in CSS with the custom variable for reliable height.
Test on real devices and update viewport height on resize events.
Avoid raw 100vh for full-height layouts on mobile browsers.