2012-07-10 205 views
10

我有两列,想要按照外观顺序堆叠不同高度的div。不同高度的div浮在两列

divs是动态创建的。

如果我只将它们浮在宽度的50%上,很快我会遇到这种情况,即div#4比传入的少数div高5倍。然后下一个div与上一个div的底部对齐。

我需要适合孩子的div容器是这样的精确匹配:

----- ------- 
    1  2 
----- 
    3 ------- 
----- 4 
    5 
----- 
    6 
----- 
    7 ------- 
----- 8 
    9 

----- 
10 ------- 
     11 
     ------- 
     ------- 
----- 

这里是代码片段我做了什么:

<style> 
    .box {background:#20abff; color:#fff; width:50%; margin: 5px;} 
    .left {float:left;} 
    .right {float:right;} 
    .container {width:205px;} 
</style> 
    <body> 
     <div class="container"> 
      <div class="box left" style="height:60px;">1</div> 
      <div class="box left" style="height:80px;">2</div> 
      <div class="box left" style="height:30px;">3</div> 
      <div class="box left" style="height:70px;">4</div> 
      <div class="box left" style="height:60px;">5</div> 
      <div class="box left" style="height:20px;">6</div> 
      <div class="box left" style="height:40px;">7</div> 
      <div class="box left" style="height:90px;">8</div> 
      <div class="box left" style="height:30px;">9</div> 
     </div> 
    </body> 

,它看起来类似于这样

http://dl.dropbox.com/u/142343/divstack.html

欣赏帮助

+0

你能发布你目前的html和css吗? – Erica 2012-07-10 13:47:04

+0

[你有什么尝试?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – avall 2012-07-10 13:50:19

+0

我明白你想要做什么..虽然有什么问题吗? – Oofpez 2012-07-10 13:51:13

回答

12

你将不得不用JavaScript来做到这一点。如果您使用的是jQuery,则会有一个名为Masonry的优秀插件。还有non jQuery version

引述README on GitHub

砌体是一个动态的网格布局脚本。把它看作CSS浮动的倒装端 。而浮动水平排列元素,然后垂直排列元素,砌体垂直排列元素,将每个元素放置在网格中的下一个未打开位置。结果最大限度地减少了不同高度元素之间的垂直间隙,就像墙壁上镶嵌石块的泥瓦匠 一样。

single column layout可能是你要找的。


如果你不介意在尘土上留下旧的浏览器,还有CSS3 column properties。有一个例子here, on Quirksmode,以及MDN的一些文档。

+0

+1砌体插件是这种布局的方式。 – 2012-07-10 13:58:26

+0

但砌体不能在IE中工作...任何解决方案 – 2013-01-05 10:25:01

+0

@Rama你甚至在IE中试过吗? [演示网站](http://masonry.desandro.com/)在IE10,8和7中完美工作。 – Bojangles 2013-01-05 10:27:21

2

使用2 div作为容器,把这两个列在这个容器div,所以给这个div浮动左右....它可能工作... 此外网格布局将工作。