如何对齐具有不同高度的div?

时间:2013-03-30 10:25:37

标签: javascript html

我需要一个Javascript代码来添加以下模型中的新DIV。我将使用默认排序,如float left,这些项目是以水平方式排序。请帮帮我

<div id="maincontainer">

<div style="height:100px;width:150px; float:left; border:1px solid red; margin:5px;">smallest</div>
<div style="height:200px;width:150px; float:left; border:1px solid red; margin:5px;">largest</div>
<div style="height:150px;width:150px; float:left; border:1px solid red; margin:5px;">middle</div>
<div style="height:100px;width:150px; float:left; border:1px solid red; margin:5px;">middle2</div>
<div style="height:190px;width:150px; float:left; border:1px solid red; margin:5px;">middle3</div>
<div style="height:160px;width:150px; float:left; border:1px solid red; margin:5px;">middle4</div>

</div>

<javascript>
$('div').sort(function (a, b) {
    return $(a).height() > $(b).height() ? 1 : -1;  
}).appendTo('body');
</javascript>

我得到的输出是

enter image description here

我需要这样

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以创建3或者您需要具有固定宽度的列,并将块放在此w / o浮动中。

例如:

<div id="first_col">
  <div class="block">
    content
  </div>
  <div class="block">
    content2
  </div>
</div>

<div id="second_col">
  <div class="block">
    content
  </div>
  <div class="block">
    content2
  </div>
</div>

<div id="last_col">
  <div class="block">
    content
  </div>
  <div class="block">
    content2
  </div>
</div>

并且通过JS将新的块添加到div中,其中高度很小。