Make body have 100% of the browser height
Want to make the body
span the full browser height? 100vh
is the secret sauce. Take a look:
In this case, we use min-height
instead of height
. Why? With min-height
, your content still can grow when it exceeds the viewport height. The vh
(viewport height) unit keeps the body as tall as the visible window—automatically responsive.
A primer on CSS cascade and inheritance
To ensure your body
can reach the full browser height, your CSS has to grasp the idea of cascade and inheritance. Applying a 100% height to the root, html
, ensures all heights are computed accurately:
Setting this up provides a consistent reference for the body
to compute its percentage-based heights, leading to a full-height layout irrespective of the content size.
Handling long stories—content overflow
In real life, content can certainly overflow with verbosity. Content that's longer than the viewport calls for min-height
rather than a fixed height
. The min-height: 100vh;
recipe lets the body stretch as needed, leaving no part of the story unread:
Keep both padding and margins for the body
at zero to maintain accurate dimensions, eliminating that annoying horizontal scrolling.
Embracing cross-browser compatibility
Like it or not, browser incompatibilities are still a thing. Before using viewport units, check their support in various browsers on Can I use. If not fully supported, lean towards position: absolute;
for a guaranteed full stretch:
Be mindful though: absolute positioning can take the element out of the document flow, potentially muddling up layout of child elements.
Borrowing the power from display tables
Did you know? CSS display: table;
can be your best friend when sizes must be dynamic. Coupled with display: table-cell;
, it allows you to realize dynamic expansion with elegance:
Using this strategy, child elements with percentage heights encounter fewer issues, as they do not have to depend on the parent's explicit height.
Pitfalls and their antidotes
In your journey to reach full height, beware of common roadblocks:
Careless handling of overflowing content
Despite our best efforts, browsers may still misbehave when content overflows, leading to clipped texts or unwanted scrolls. Be sure to validate your styles across different browsers to avoid unpleasant surprises.
Unexpected child behavior
Children (read elements) with percentage-based heights can act out when parents use min-height
instead of height
. Always test with various content lengths to ensure consistent outcomes:
Mobile viewport inconsistency
100vh
can be fickle across mobile browsers, thanks to the hide-and-seek game played by address bars. Overcome this by using apposite CSS workarounds or JavaScript fixes as discussed in CSS-Tricks articles.
Was this article helpful?