How to force child div to be 100% of parent div's height without specifying parent's height?
Use the CSS flexbox layout. Set display: flex;
on the parent div and flex: 1;
to the child div. This causes the child to take up 100% of the parent's height.
Quick implementation:
The child div's height will adapt to the parent's height. No predetermined sizes required.
Deep Dive: Methods to make Child 100% of Parent's height
Using Flexbox for magic alignment
To control individual child alignment, use align-items
or align-self
. Here's how to use them in Flexbox:
display: table-cell;
hack from the past
Before flexbox, a popular hack was display: table-cell;
:
Be aware, this path leads to challenges like controlling spacing and handling margins.
Absolute positioning: the classic trick
A classic method is using absolute positioning:
Remember to set 100%
height to HTML
and BODY
for full reference:
The challenge is managing layout intricacies that absolute positioning may bring, such as overlapping elements and stacking contexts.
Strategies for specific layout scenarios
Vendor prefixes: a necessary evil
Remember browser discrepancies? Include vendor prefixes for cross-browser flexbox compatibility:
Don't forget that legacy browsers may not support Flexbox or Grid. You might need to fall back to our friend, display: table-cell;
.
"Faux-columns": a clever illusion
Use the "faux-columns" technique to create visually equal-height columns:
This maintains visual consistency even with minimal content.
Dynamic world, dynamic content
Avoid fixed heights with dynamic content like PHP output or user-generated content. The flexibility of Flexbox and Grid allows your layout to respond to content changes:
Was this article helpful?