使用 float 水平排列 DIV 很容易。例如:
<div style="width: 500px;">
<div style="float:left; width: 200px; height: 100px; background-color:Yellow;"></div>
<div style="float:left; width: 150px; height: 60px; background-color:Blue;"></div>
<div style="float:left; width: 140px; height: 240px; background-color:Green;"></div>
<div style="float:left; width: 180px; height: 200px; background-color:Red;"></div>
<div style="float:left; width: 130px; height: 160px; background-color:Purple;"></div>
</div>
这将产生:
但是如何水平和垂直排列 DIV?在这种情况下,如何将红色和紫色 DIV 移到有空白空间的上方(在黄色和蓝色 DIV 下方)?
注意:这只是一个例子,我希望找到一种方法来对任何一组DIV进行排列(不仅仅是这个典型的例子)。
最佳答案
假设您正在处理一组动态的任意大小的对象,没有纯 CSS 方法可以实现这一点。在以下情况下,您可以使用 CSS3 多列布局来接近:
- 您只需要支持现代浏览器。
- 所有对象都可以排列成等高的组。
在这里,对象以 300px 高度为一组排列。
<div id="blocks">
<div style="height: 100px; background-color: yellow;"></div>
<div style="height: 200px; background-color: blue;"></div>
<div style="height: 300px; background-color: green;"></div>
<div style="height: 200px; background-color: red;"></div>
<div style="height: 160px; background-color: purple;"></div>
</div>
#blocks {
-moz-column-count: 3;
-moz-column-gap: 0;
-webkit-column-count: 3;
-webkit-column-gap: 0;
column-count: 3;
column-gap: 0;
width: 450px;
}
#blocks div {
width: 150px;
}
关于css - 两个方向的DIV紧凑排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222859/