3fjorq
Last Updated: February 25, 2016
·
1.004K
· chocopie

Use overflow:auto; to expand the parent of floated elements

You know that problem where you have all floating elements in a parent div, and the parent doesn't expand to fit the size of its children? It's super irritating when you need that parent to provide background styling or to make other elements on the page fall in line.

The most bug-free fix I've found:

overflow: auto;

Apply this to the parent and remove any fixed height. BAM!! Nice expanding with decent respect for paddings and margins.

I'm surprised when I meet skilled webdevs who don't know this hack. They typically opt for clear: both;, which should work in theory, but I'm skeptical. I've seen clear: both; do funny things when there are many elements using it. The most puzzling one is where you get a huge gap between elements for no apparent reason.

But overflow: auto; on the parent seems to work every time.

2 Responses
Add your response

2424

You can also do overflow: hidden; for the same effect.

The advantage is that you won't accidentally trigger scrollbars in some circumstances. (The disadvantage is that you may be truncating content in those cases instead. But these cases are rare anyway.)

over 1 year ago ·
2590

@garrettl Thank you! Scrollbars only seem to come up if a line of unbroken text appears (eg. a long-ass error code) or if there's an unexpected oversized image. I guess the chances of truncating would be similar. Much love for overflow. <3

over 1 year ago ·