Styling HTML and BODY selector to height: 100%; vs using 100vh
The height: 100vh;
CSS property makes an element span the complete viewport's height, irrespective of parent properties. On the other hand, height: 100%;
requires a parent with a defined height, which is not guaranteed to be the viewport. To ensure complete coverage, 100vh
is direct and prevents calculation errors.
However, the actual value of 100vh
might differ on mobile devices due to visible and hidden address bars. Scrollbars might impact vw
units on desktop screens, leading to layout shifts.
Understanding the differences
Viewport vs Parent-dependent Units
Viewport units (vw, vh, vmin, vmax) are dynamically calculated based on the viewport dimensions, while height: 100%
is calculated as a proportion of the parent element's height. For the latter to fill the viewport, the height of every ancestor (including <html>
and <body>
) must be set to 100%.
Adapting to screen changes
Viewport units bring a big advantage for creating responsive designs that adjust to any screen size. For example, vw
units for font sizes can create a flexible typography scheme, which adapts to the viewport:
Nonetheless, when orientating changes on a device or toolbar visibilities shift on mobile, 100vh
can also change.
Handling Scrollable Content
height: 100vh
can cause overflow and scrolling issues with content taller than the viewport. It's crucial to manage this by utilizing CSS techniques to handle overflow, setting height based on JavaScript's window.innerHeight
, or calculating heights.
Real-world uses for 100vh
and 100%
Fullscreen Layouts
The 100vh
measurement can create impressive full-screen sections fitting the complete viewport height. These are great for landing pages or hero sections intended to create a memorable impact.
Nested Factory
When dealing with nested elements in complex layouts, it's better to use height: 100%
. This provides a consistent and logical cascade of inherited properties from parent to child elements. One size can indeed fit all!
Mobile Browsers and Toolbars
On mobile screens, address bars appear and disappear, changing 100vh
accordingly. Listen for the resize events and dynamically adjust your heights, or use CSS's env() function for safe areas on iOS devices.
Scrollable is Sayable
Creating a scrollable container within a full-screen viewport element is possible by pairing 100vh
with overflow: auto
. This guarantees that the container is always exactly the size of the viewport, but allows internal scrolling if the content exceeds 100vh
.
Was this article helpful?