Explain Codes LogoExplain Codes Logo

How to force child div to be 100% of parent div's height without specifying parent's height?

html
responsive-design
flexbox
css-hacks
Alex KataevbyAlex KataevΒ·Oct 14, 2024
⚑TLDR

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.

.parent { display: flex; /* Cool kids use flex. πŸ‘ */ } .child { flex: 1; /* I grow like a well-watered plant! 🌱 */}

Quick implementation:

<div class="parent"> <div class="child"> <!-- Your content here --> </div> </div>

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:

.parent { display: flex; align-items: stretch; /* default, makes all kids behave */ } .child { align-self: auto; /* because some kids like to rebel */ }

display: table-cell; hack from the past

Before flexbox, a popular hack was display: table-cell;:

.parent { display: table; } .child { display: table-cell; height: 100%; /* our inner div is now an obedient 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:

.parent { position: relative; } .child { position: absolute; top: 0; bottom: 0; /* What goes up, must come down */ }

Remember to set 100% height to HTML and BODY for full reference:

html, body { height: 100%; /* Keep calm and stretch on */ }

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:

.parent { display: -webkit-flex; /* Hi Safari */ display: -ms-flexbox; /* Hello Edge */ display: flex; /* Hey everybody else */ }

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:

.parent { background-image: linear-gradient(to right, #f7f7f7 10em, white 10em); } .child { padding-left: 10em; /* AAAH! A wild column appears */ }

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:

.parent { display: flex; /* Still flexin'! */ flex-wrap: wrap; /* can I get a line break? */ } .child { flex: 1; /* Size does matter */ min-width: 200px; /* slim-fit */ }