tags:

views:

27

answers:

3

The idea: I have a container div with two divs inside of it, like two columns on a page.

The issue: I have to use the CSS 'float' property in order to get the two divs to display next to each other, but when I apply float:left or right to the divs the parent div, which is not floated, does not get stretched to the size of the child divs, so the background disappears. I know a Javascript trick to solve this, but are there any simple, clean CSS solutions that I'm missing?

+3  A: 

Adding overflow:auto to the parent should work.

Adding something like this right after floated elements works:

<div>
    <div style='float:left;'></div>
    <div style='float:right;'></div>
    <div class='clear;></div>
</div>

Then just add .clear class to your css:

.clear{
    clear:both;
}
GaVrA
Excellent, works perfect! Many thanks.
Will
@Will dont forget to mark one of the answers as the accepted answer. ;)
GaVrA
Hehe, of course! It was just giving me a "please wait 5 minutes before answering" because you were so speedy!
Will
+2  A: 

Using a clearfix technique should successfully stretch down your parent element.

You could either add a clearing element to the bottom of the parent:

HTML

<div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="clear"></div>
</div>

CSS

.clear { clear: both }

Or you could apply a CSS clearfix hack to the parent element.

CSS

.parent { overflow: auto }

In a sense, it's a trade-off. Which feels more hackish: extra markup, or CSS that kinda just happens to do what you want?

Matchu
Less the better, I always say.
Will
A: 

Use display:inline-block instead of float. inline-block applied to block elements make them appear inline. So, if you container has class container you need to use the following CSS:

.container div
{
     display:inline-block;
}

For IE6 and 7 you can use only display:inline, it behaves the same way as inline-block.

Genady Sergeev
A fully cross-browser compatible inline-block can be rather complicated to pull off, and [ends up involving tons of hacks](http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/). While inline-block is definitely better in certain situations, floats can sometimes actually be far, far simplier.
Matchu
Genady Sergeev