Collapsing Divs or Why is My Div Height 0 (zero)?

Content

Collapsing Divs or Why is My Div Height 0 (zero)?

Posted in:

Not coding in CSS on a permanent basis means that there are some things that always trip me up when I flop back into CSS. And 0 height divs are the main offender.

Normally a div contains its content and will have a height large enough to enclose the said content. If the div contains only floated content however then the div height will be zero. The reason for this is that floating, by definition, takes the floated element out of the regular flow of the layout. The parent div remains the parent but does not extend to contain its floated children.

The effect of this is instantly noticeable if you try and set the background-color for a div containing only floated content. The div height is zero so the background colour is not displayed. If the parent element contains non floated elements before the floated elements then the div will generally extend to accommodate them. Other non floated elements that exist after the floated elements seem not to be accommodated.

The most cross platform friendly solution is to add the following additional overflow and width attributes to the container div.

div.container {
	overflow: auto;
	width: 100%;
}

div.left {
	width: 45%;
	float: left;
}

div.right {
	width: 45%;
	float: right;
}
The CSS visual formatting model is the basic reference for all this. I also need to remind myself from time to time that floated divs expand to fit their content horizontally. A non floated div automatically stretches to fill its container horizontally. When laying out columns we give a floated div a width because we want to constrain the layout to the width of the column. In other cases, such as when floating horizontal menu items, we want the floated divs to extend to contain their content.