CSS viewport units (vw, vh, svh): what they do and when to use them

Master CSS viewport units like vw and vh, and learn how dynamic units like svh and lvh solve common mobile layout bugs.

CSS viewport units provide a mechanism to size elements relative to the browser window's dimensions, independent of the DOM hierarchy. The base units are vw (viewport width) and vh (viewport height). One vw equals 1% of the width of the viewport, while one vh equals 1% of the height. For example, setting an element to width: 100vw ensures it strictly spans the entire width of the visible window.

Viewport units are uniquely suited for full-screen hero sections, modal overlays, and fluid typography. However, utilizing 100vw can sometimes introduce horizontal scrolling if a vertical scrollbar is present, because the viewport width calculation does not consistently subtract the scrollbar's width across different operating systems and browsers.

The 100vh mobile browser bug

For years, web developers struggled with a notorious issue on mobile browsers when using height: 100vh. On mobile devices, the browser address bar dynamically expands and retracts as the user scrolls. Unfortunately, the standard vh unit is calculated based on the maximum possible viewport height, ignoring the space occupied by the expanded address bar.

As a result, a full-screen layout set to 100vh on a mobile device will have its bottom portion cut off and hidden beneath the browser UI when the page first loads. Developers historically relied on complex JavaScript hacks to calculate innerHeight and assign CSS custom properties just to keep content visible on screen.

The solution: svh, lvh, and dvh

To resolve the mobile UI issue, modern CSS introduced new dynamic viewport units. The 'svh' (Small Viewport Height) unit represents the viewport size when all dynamic browser interfaces are expanded, ensuring content is never hidden. Conversely, 'lvh' (Large Viewport Height) represents the viewport size when the browser UI is retracted.

The 'dvh' (Dynamic Viewport Height) unit continuously adapts as the user scrolls and the browser UI expands or collapses. While dvh offers the most accurate physical representation, it can cause layouts to visibly jump or trigger expensive browser repaints during scrolling. For most reliable full-screen mobile layouts, using height: 100svh is the recommended best practice to guarantee visibility.