tags:

views:

196

answers:

2

I'll try to explain this as best I can. I have multiple divs that are fixed-width but variable height. I want to float these boxes into two columns inside a fixed-width container. What happens when a give them all a float: left value, I get something like this:

######### ######### 
# box 1 # # box 2 # 
######### # ..... # 
......... # ..... # 
......... ######### 
######### ######### 
# box 3 # # box 4 # 
# ..... # # ..... # 
######### #########
######### #########
# box 5 # # box 6 #
# ..... # #########
# ..... #
#########

(The periods are white space)

What I really would really like is the top of box 3 to touch the bottom of box 1. Any easy way to acheive this?

Edit: Would like to find a solution that works for more than 2 columns. The perfect soution woudl work with an elastic layout and spread to as many columns as would fit on the screen horizontally.

A: 

Instead of working horizontally, work vertically.

Now:

L     R
1 ==> 2
3 ==> 4
5 ==> 6

Other way:

L   R
1   2
\/  \/
3   4
\/  \/
5   6

So basically, put all the odd divs in the left column, all the even divs in the right column. If you create these divs dynamically, first group them by odd and even, and then add them to the appropriate column.

Alec
Hi Alec--yes, the divs are created dynamically so I was trying not to have to do any extra processing not not necessary. I was hoping CSS could handle it for me. Seems this may be my only choice though to change the dynamic creation of the divs.
Jeremy H
+1  A: 

You need to alternate left and right floating on your boxes.

  .box:nth-child(2n+1){
    float: left;
  }
  .box:nth-child(2n){
    float: right;
  }

Warning this code is not compatible with older browsers, for those you might want to set a different CSS classes programmatically every other box.

Guillaume Esquevin
Wow, that's crazy. Never seen CSS like that. Any way to make this work with 3 columns instead of 2? Seems like with the left/right float changing it wouldn't work with a 3rd middle column.
Jeremy H
You could try with a middle column without any float behavior, so it will stay in the middle. .box:nth-child(3n+1){ float: left; } .box:nth-child(3n){ float: right; }But at some point you may need to take advantage of CSS3 column properties (currently available only for mozilla or webkit based browsers) -webkit-column-count: 3;
Guillaume Esquevin