views:

235

answers:

6
+3  Q: 

side by side divs

I've got 4 divs inside a parent div. To get them to appear side by side, I've given all 4 divs a style with float:left. The divs do appear side by side, but the parent div's height does not grow to encompass the height of the child divs. What am I missing?

A: 

I think you should give the parent div a height of 100% not fixed so that it encompasses the height of child divs if they grow.

Sarfraz
+1  A: 

Set overflow: hidden; on the parent div.

Explanation: floating elements removes them from the regular document flow. So, if a given element contains only floated elements, it will not have any height (or, by extension, width -- unless it has an implicit width that is default on block elements).

Setting the overflow property to hidden tells the parent element to respect the width of it's children, but hide everything that falls outside it's width and height.

Of course, the other option is to add an element after the floated divs, inside the parent, with clear: both; This makes the last element be positioned after all the floats, within the regular document flow. Since it's inside the parent, the parent's height is whatever the heights of the floated items are, plus regular padding and the height of the cleared item.

davethegr8
+3  A: 

After the 4 divs, you need to "cancel" the float style. This is done through the creation of a p for example, like: <p style="clear: both"></p> Your parent div will automatically get the right size.

millinet
you obviously meant `clear:both`
Marek Karbarz
This isn't the recommended solution by most web developers, as it requires extra empty markup that junks up the document.
zombat
+3  A: 

This is a quirk cause by the implementation of floating elements, and occurs when you have a parent element that contains nothing but floating child elements. There are two methods to solve it. One is to set the parent element's overflow property to hidden, sometimes known as the overflow method. The other is known as the clearfix method, and involves the use of the :after pseudo-class.

The clearfix method has the advantage of allowing for specifically positioned elements to "hang" outside of the parent container if you ever need them to, at the expense of a bit of extra CSS and markup. This is the method I prefer, as I utilize hanging elements frequently.

zombat
+1  A: 

millinet's answer will work, or you could float the parent div which will also allow it to expand to contain its content

Ray
A: 

I recommend the clearfix method as well. This problem occurs because floating an element removes any height that it would normally contain.

PositionIsEverything posts a complete explanation as well as corresponding solutions for IE6, since the :after pseudoselector is not supported by older browsers.

neatlysliced