tags:

views:

462

answers:

3

This is just a basic question, but I've had this happen to me a couple times and would like to know why.

Say you have a div, say you color it green and give it a definite width, when I put stuff within it, in my case an img and another div. The idea is that the content of the container div will cause the container div to stretch out, and be a background for the contents. But when I do this, the containing div shrinks to fit the non-floating objects, and the floating objects will be either all the way out, or half out, half in, and not have any bearing on the size of the big div.

Why is this? Is there something I'm missing, and how can I get floated items to stretch out the height of a containing div?

+3  A: 

The easiest is to put overflow:hidden on the parent div and don't specify a height:

#parent { overflow: hidden }

Another way is to also float the parent div:

#parent { float: left; width: 100% }

Another way uses a clear element:

<div class="parent">
   <img class="floated_child" src="..." />
   <span class="clear"></span>
</div>

CSS

span.clear { clear: left; display: block; }
Doug Neiner
Syntax-highlighting fail... The equivocal # strikes again! :)
Jonathan Sampson
It works, but now I'm twice as confused: is there an explanation for this or is this just how it is?
DavidR
Yes, there is an explanation but I have since forgotten it :( Its just how it is. The `overflow:hidden` forces the browser the best it can to contain the child elements of the parent. Thats why it fixes it.
Doug Neiner
+2  A: 

There's nothing missing. Float was designed for the case where you want an image (for example) to sit beside several paragraphs of text, so the text flows around the image. That wouldn't happen if the text "stretched" the container. Your first paragraph would end, and then your next paragraph would begin under the image (possibly several hundred pixels below).

And that's why you're getting the result you are.

Lucas Richter
A: 

As Lucas says, what you are describing is the intended behaviour for the float property. What confuses many people is that float has been pushed well beyond its original intended usage in order to make up for shortcomings in the CSS layout model.

Have a look at Floatutorial if you'd like to get a better understanding of how this property works.

Sam Murray-Sutton