Explain Codes LogoExplain Codes Logo

Stretch child div height to fill parent that has dynamic height

html
responsive-design
flexbox
css-grid
Nikita BarsukovbyNikita Barsukov·Mar 7, 2025
TLDR

For a child div to fill the parent's height, CSS flexbox serves as a quick solution. Assign display: flex; to the parent and flex-grow: 1; to the child. This configuration enables the child div to dynamically stretch to fully occupy the parent.

.parent { display: flex; flex-direction: column; /* Just playing accordion with divs */ } .child { flex-grow: 1; /* I'm like a yoga master, flexing to fill up space */ }
<div class="parent"> <div class="child"> <!-- I'm stretching up just like you do in your 7AM Yoga class!!! --> </div> </div>

Flex-grow is the linchpin here: it allows the child div to adapt with grace to the dynamic height of the parent.

Stretching beyond basics: Unpacking Flex and Grid

Not only does the display: flex attribute magically morph the parent div into a flexible layout for its children, but it also empowers child divs to match the available space - especially when flex-grow is enforced.

Let's talk about align-items

.parent { display: flex; align-items: stretch; }

Here, align-items: stretch presents another method to ensure child divs filler-up the parent's height - this time, without even speaking flex-grow into existence!

Staying responsive

Flexbox truly shines when it comes to crafting responsive designs. A similar feat can be achieved using CSS Grid. It's another powerhouse when tending to match-height child divs:

.parent { display: grid; /* Establishing the grid lines */ } .child { align-self: stretch; /* Doing a stretch, Jane Fonda style! */ }

Dynamic height solutions demystified

Flexing wisdom with justifications

Just like in life, in flexbox, every justify-content adjustment changes the layout in a new way. For instance, space-between manipulates spacing and alignment within the parent div. Thus, use such properties with diligence, as missteps can alter the stretching behavior of the child divs.

Maintaining responsiveness

While embracing flexbox or grid, always strive to keep the responsive design in check. These dynamic layout techniques react splendidly to different screen sizes, bolstering your design to be adaptive and user-friendly.

Flexbox and Grid: Layout saviors

Flexbox and grid can save you from the abyss of layout challenges. Apart from endowing child divs the gift of responsivity to the parent's fluctuating size, they also ensure uniform height distribution.

#container { display: flex; /* Look, Ma! Flexing my divs */ } .content { /* Adjusting the width, padding, for a chic look */ }