20

My question arose when I created my (first ever!) two columns.

I have a wrapper for my left and right columns, but the wrapper's height didn't expand to fit the left and right columns with each floated to its side respectively.

I found a solution online where it adds the style (is this the right word?) 'overflow: auto' to the wrapper. After some research, I've found several articles that explain what the overflow does, including this stackoverflow answer:Why "overflow: hidden" clears a float?

However, nothing in my research explains in a way I can understand why the wrapper's height doesn't auto-expand to fit the nested divs, the two columns.

Don't all things nested within a div are contained within that div? Doesn't this create boundaries for the inside elements?

Any help is appreciated for this noobie. Thanks!

braX
  • 11,506
  • 5
  • 20
  • 33
Atlas2k
  • 381
  • 2
  • 13
  • 3
    `overflow: auto` as a whole is known in CSS nomenclature as a [declaration](http://www.w3.org/TR/CSS21/syndata.html#declaration), but calling it a "style" is fine as long as there's no ambiguity. – BoltClock Mar 02 '14 at 15:30
  • 2
    Here is a playground for all of you: http://jsfiddle.net/ADxx9/ – Nico O Mar 02 '14 at 15:34
  • 1
    Here's a page that also discusses it ('old' and 'new' solutions)- http://www.quirksmode.org/css/clearing.html. But Nico O's fiddle is fantastic, and Boltclock's answer below is superb. – TimSPQR Mar 02 '14 at 15:48
  • Thanks for the nomenclature explanation! – Atlas2k Mar 03 '14 at 02:16

1 Answers1

34

The reason why the wrapper doesn't stretch to contain its floats by default is because the floats are taken out of the normal flow of the wrapper, so the wrapper acts as if they were never there. If there is no other content in the wrapper, that means the wrapper won't have any height.

Note that overflow: auto doesn't clear floats — it just causes the element to contain its floats by way of establishing a new block formatting context for them so that they don't intrude to other elements in the parent context.1 That is what forces the parent to stretch to contain them. You can only clear a float if you add a clearing element after the float. A parent element cannot clear its floating children.

The reason why establishing a new BFC causes an element to contain its floats is detailed here, and the reason why overflow: auto would even cause a BFC to be established is detailed here.


1 OK, maybe "just" wasn't exactly the best adverb to use.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • How come floats are taken out of the normal flow of the wrapper? – Atlas2k Mar 03 '14 at 02:23
  • 1
    @Atlas2k: Doing so allows any inline content to flow alongside it even if they don't share the same wrapper elements. See [this diagram](http://www.w3.org/TR/CSS21/visuren.html#img-float2p) for an example. – BoltClock Mar 03 '14 at 03:22