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.

Jeremy H
  • 1,784
  • 4
  • 17
  • 27

2 Answers2

3

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
  • 2,992
  • 20
  • 25
  • 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 May 12 '10 at 15:33
  • 1
    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 May 17 '10 at 11:36
  • The problem with this solution is it won't allow for optimal box placement. For example, even if box 3 is vertically large enough that it could accomodate box 4 and box 5, box 5 will still get kicked to the left side. I'm looking for a solution that optimizes the placement, and I'm sure Jeremy too is looking for the same thing. – syockit Mar 05 '11 at 08:47
  • Amazing! Just what I was looking for! – killerkiara Nov 23 '16 at 15:32
0

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
  • 9,000
  • 9
  • 39
  • 43
  • 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 May 11 '10 at 02:06