Expanding a parent <div> to the height of its children
To make a parent <div> automatically adapt to its children's height, implement CSS Flexbox. Set the parent to display: flex; and its height will be dictated by the total height of the child elements:
This approach ensures the parent <div> expands and contracts based on its children.
Overflow control
To keep scrollbar issues at bay, apply overflow: auto; to your parent <div>:
Tabular alignment options
Another way to achieve this is by using display: table; for the parent <div> and display: table-row; for child <div>—like a strict school teacher ensuring the students (child <div>) line up properly:
Containing content
For a parent <div> that perfectly wraps around its content, use height: max-content;:
Clearing floating kids
When your child elements are floating around, incorporate clear: both; in a pseudo-element inside the parent and get it back under control:
Don't forget to remove overflow: auto if the scrollbar is not needed!
Inline-block Solution
A time-tested way that survives any browser compatibility test — setting the parent <div> to display: inline-block;;
Managing extra heights
When flexibility is key, don't limit yourself with a fixed height. Turn to min-height to allow the parent to expand with the content:
Tools for page-level scrolling
Sometimes, it's more user-friendly to have the entire page scroll instead of a particular <div>. This is the case for full-page layouts:
Implementing changes
We'll now link you up to a jsfiddle example to look at a practical application of these techniques.
Advanced tactics with will-change
When making performance optimizations, consider will-change to tell the browser what properties are expected to change:
Deep dive into flexbox wraps
If you're dealing with multiple children that can wrap into new lines, flexbox has a trick up its sleeve with flex-wrap:
This allows the children to 'jump' onto a new line when there's no room left!
Was this article helpful?