Make a div fill the height of the remaining screen space
Leverage CSS Flexbox to fill available vertical space. Set the parent container with display: flex; flex-direction: column; height: 100vh;
and target div
gets flex-grow: 1;
.
Here, the .stretch
div
soaks up all unused vertical space within the .container
like a sponge.
Laying the groundwork
Setting the stage
Ensure the html
and body
tags are set to height: 100%
to cover the full viewport. This anchors child elements to calculate their relative height.
Flexbox magic
Handle dynamic header heights by setting the #header
to flex-grow:0
and the #content
div
to flex: 1 1 auto
.
Overflow: Covered
Should your content overflow, use a .scroll-y
class with overflow-y: auto;
on the #content
div.
Nitty-gritty of height handling
Calc saves the day
With fixed-size headers or footers, use calc(100% - header-footer height)
for the #content
height to perfectly fill available space.
Keeping up with the browsers
Ensure Flexbox support across browsers via Can I use. For the legacy browsers, use -ms-
prefixed properties or a polyfill like FlexieJS, or alternate CSS tables.
Responsive is responsible
Implement CSS @media
queries to accommodate varying screen sizes. Encourage design flexibility across all devices.
Fallback strategies
In case of Flexbox-resistant browsers, a robust fallback layout is essential. Use CSS tables as a similar, supportive fallback layout.
Was this article helpful?