Viewport Units
Overview
Sometimes you need an element to size itself based purely on the physical screen size, ignoring its parent container entirely. Viewport units (vw, vh) represent 1% of the viewport width or height. This is crucial for creating Full-Screen Hero Sections (height: 100vh). However, mobile browsers introduced a massive bug: the URL bar disappears when you scroll, changing the physical height of the screen! Modern CSS introduced dvh (Dynamic Viewport Height) to solve this dreaded mobile scroll bug.
Syntax
/* 100vw = 100% of the screen width */
.full-bleed-image {
width: 100vw;
}
/* 100vh = 100% of the screen height (Buggy on mobile iOS/Android) */
.hero-section-old {
height: 100vh;
}
/* 100dvh = Dynamic Viewport Height (The Modern Fix!) */
/* Automatically recalculates when the mobile URL bar shrinks/grows */
.hero-section-new {
height: 100dvh;
}
/* Small Viewport (Height excluding the URL bar) */
.modal {
height: 100svh;
}Common Pitfalls
- Using
width: 100vwinstead ofwidth: 100%on the<body>. On Windows desktop, the scrollbar takes up physical space (usually 15px).100vwcompletely ignores the scrollbar and measures the full screen width, pushing 15px of your content off the screen and triggering a nasty horizontal scrollbar. Always use100%for width. - Using
vhfor full-screen mobile menus. When the URL bar pops up on an iPhone, the bottom 20% of your menu (including the submit button) will be physically hidden under the browser UI. Always use100dvhfor mobile full-screen layouts.
Interview Questions
dvh (Dynamic Viewport Height) unit introduced to CSS?To solve the mobile browser URL bar issue. Mobile browsers retract their UI (URL bar/bottom nav) when scrolling down, physically changing the viewable height of the screen. 100vh remained static and broke layouts. 100dvh dynamically recalculates the exact available pixels in real-time.
Real-World Example
A bulletproof full-screen modal wrapper that works flawlessly on iOS Safari.
.mobile-modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
/* svh (Small Viewport Height) ensures the modal NEVER gets hidden
under the mobile browser's address bar. */
height: 100svh;
background: rgba(0,0,0,0.8);
}Check Your Knowledge
Test your understanding of Viewport Units with these quick questions.