Explain Codes LogoExplain Codes Logo

Make a div fill the height of the remaining screen space

html
responsive-design
css
flexbox
Alex KataevbyAlex Kataev·Nov 5, 2024
TLDR

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;.

.container { display: flex; flex-direction: column; /* Stack like pancakes */ height: 100vh; /* Full viewport height */ } .stretch { flex-grow: 1; /* Takes the "eat what your siblings don't" approach */ }
<div class="container"> <div>Top Content</div> <div class="stretch">Expands to fill space</div> <div>Footer Content</div> </div>

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.

html, body { height: 100%; /* Full viewport coverage like sunblock */ }

Flexbox magic

Handle dynamic header heights by setting the #header to flex-grow:0 and the #content div to flex: 1 1 auto.

#header { flex-grow: 0; /* Keeps header on a strict diet */ } #content { flex: 1 1 auto; /* Content, Y U NO EAT */ }

Overflow: Covered

Should your content overflow, use a .scroll-y class with overflow-y: auto; on the #content div.

.scroll-y { overflow-y: auto; /* If it overflows, scroll (modern problems need modern solutions) */ }

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.

#content { height: calc(100% - 120px); /* We <3 calc. Assuming header and footer = 60px each */ }

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.