css - 两个方向的DIV紧凑排列

标签 css html css-float

使用 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>

这将产生: enter image description here

但是如何水平和垂直排列 DIV?在这种情况下,如何将红色和紫色 DIV 移到有空白空间的上方(在黄色和蓝色 DIV 下方)?

注意:这只是一个例子,我希望找到一种方法来对任何一组DIV进行排列(不仅仅是这个典型的例子)。

最佳答案

假设您正在处理一组动态的任意大小的对象,没有纯 CSS 方法可以实现这一点。在以下情况下,您可以使用 CSS3 多列布局来接近:

  1. 您只需要支持现代浏览器。
  2. 所有对象都可以排列成等高的组。

在这里,对象以 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;
}

http://jsfiddle.net/RTLun/

关于css - 两个方向的DIV紧凑排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222859/

相关文章:

html - CSS - 与 float 对齐

javascript - 我正在尝试验证 jsp 登录表单,我需要字段(标签)验证而不是警报消息

JQuery 鼠标悬停图像叠加

javascript - 如何通过 HTML 表单输入文本并使用 Javascript 从 JSON 文件中检索数据作为响应?

python - 未找到 Django Python 页面 (404)

html - 调整网页上的 float 元素

javascript - 在一定百分比上禁用 Bootstrap Progress Bar 的平滑动画过渡

html - 背景图片不动

html - 子菜单不显示,搜索菜单在同一行

html - 能够始终如一地 float td 元素?