Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

css - Compact arrangement of DIVs in two directions

It is easy to arrange DIVs horizontally with float. For example:

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

This will produce: enter image description here

But how to arrange the DIVs both horizontally and vertically? In this case, how to shift the Red and Purple DIVs upper where there is empty space (under Yellow and Blue DIVs)?

NOTE: This is just an example, and I wish to find a method to make the arrangement for any set of DIVs (not only this typical example).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you are working with a dynamic set of arbitrarily sized objects, there is no pure CSS method to achieve this. You can get close by using a CSS3 multi-column layout if:

  1. You only need to support modern browsers.
  2. All objects can be arranged into equal-height groups.

Here, objects are arranged in groups of 300px height.

<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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...