views:

2224

answers:

5

Hi Everyone:

I have been attempting to split a div into two columns using CSS, but I have not managed to get it working yet. My basic structure is as follows:

<div id="content">
  <div id="left">
     <div id="object1"></div>
     <div id="object2"></div>
  </div>

  <div id="right">
     <div id="object3"></div>
     <div id="object4"></div>
  </div>
</div>

If I attempt to float the right and left divs to their respective positions (right and left), it seems to ignore the content div's background-color. And other code that I have tried from various websites doesn't seem to be able to translate to my structure.

Thanks for any help!

+2  A: 

When you float those two divs, the content div collapses to zero height. Just add

<br style="clear:both;"/>

after the #right div but inside the content div. That will force the content div to surround the two internal, floating divs.

Rob Van Dam
Thanks Rob, it works great!
PF1
+3  A: 

Another way to do this is to add overflow:hidden; to the parent element of the floated elements.

overflow:hidden will make the element grow to fit in floated elements.

This way, it can all be done in css rather than adding another html element.

tybro0103
A: 

USe style="clear:both

Faseeh
A: 

Floats don't affect the flow. What I tend to do is add a

<p class="extro" style="clear:both">possibly some content</p>

at the end of the 'wrapping div' (in this case content). I can justify this on a semantic basis by saying that such a paragraph might be needed. Another approach is to use a clearfix CSS:

#content:after {content: ".";
 display: block;
 height: 0;
 clear: both;
 visibility: hidden;}
#content {display: inline-block;}
/*  \*/
* html #content { height: 1%;}
#content {display: block;}
/*  */

The trickery with the comments is for crossbrowser compatibility.

Gazzer
A: 

For whatever reason I've never liked the clearing approaches, I rely on floats and percentage widths for things like this.

Here's something that works in simple cases:

#content { 
  overflow:auto; 
  width: 600px; 
  background: gray; 
} 

#left, #right { 
  width: 40%; 
  margin:5px; 
  padding: 1em; 
  background: white; 
} 

#left  { float:left;  }
#right { float:right; } 

If you put some content in you'll see that it works:

<div id="content">
  <div id="left">
     <div id="object1">some stuff</div>
     <div id="object2">some more stuff</div>
  </div>

  <div id="right">
     <div id="object3">unas cosas</div>
     <div id="object4">mas cosas para ti</div>
  </div>
</div>

You can see it here: http://cssdesk.com/d64uy

pat