How to make a floated div 100% height of its parent?
Your need is to make a child div
reach the 100%
height of the parent. Flexbox is the key. Give the parent the property display: flex;
and the child will stretch to full height at once. No setting of height on the parent required:
This flex
property on the child element says "Bye" to float
and works smoothly even when the parent height is ambiguous.
The parent-child bond in CSS: Understanding Flexbox
In the flex world, the .parent
div is the flex container and the .child
div is the flex item. When you set flex: 1;
on the child, you're telling it to grow and occupy all of the space available within the parent, effectively matching its height.
The code speaks multiple browser-languages: Cross-browser compatibility
Flexbox does care about everyone, even every browser. So, to ensure that your layout looks the same across all of them, consider cross-browser compatibility:
A time travel to IE9 and earlier: Flexbox support
Take note that Flexbox doesn't exist in IE9 and earlier versions. As a fallback method, you may want to go old school using display: table;
for the parent and display: table-cell;
for the child, mimicking flex-like prowess.
Departing from Flexbox: More ways to match parent height
"I got you covered!" - Absolute Positioning
If Flexbox isn't right for you, find peace in good old absolute positioning:
This covers the parent from edge to edge. Just remember that absolute positioning makes the child leave the normal document flow.
A table can be a flexbox too: Table-cell approach
When flexbox and absolute positioning don't fit your schedule, try the display: table;
and display: table-cell;
approach:
No flex and position manipulation, just plain old table display doing the same magic trick.
Corner cases: Things to keep in mind
Old browser hearty layout: Flex behavior in legacy browsers
If you're haunted by the past (aka older browsers like IE9), you can use polyfills to give them the power of modern features. Or, let your layout gracefully degrade in these environments. They'll appreciate your attention.
No explicit height required, but...
Keep in mind that child elements default to align-self: auto
in a flex container. This value will inherit the value of the align-items
property set on the parent. By default, align-items: stretch
is set, making children fill the container.
Squeeze in through padding
If absolute positioning is your weapon of choice, you can use padding on the parent to ensure it envelops the child comfortably.
Is height really 100%?
When setting height: 100%
on an absolutely positioned element, remember that it calculates from the nearest positioned ancestor (not always the direct parent).
Was this article helpful?