如何均匀地在两列中显示动态内容?

时间:2015-04-13 19:30:47

标签: javascript jquery html css multiple-columns

我在页面上加载了动态内容,因此未指定数量的元素。我需要将它们在两列之间均匀分布,所以我认为将它们的宽度设置为50%并将它们向左浮动就可以了。

<div class="element">
    <p>My content goes here!</p>
</div>

.element{float:left;width:50%;}

一个例子: https://jsfiddle.net/fft75mu4/

但是在我的例子中,蓝色元素上方有一个间隙,因为正确的元素比第一个元素高。推荐的解决方案是什么?我认为这是一个常见问题?

我宁愿不在CSS中创建实际的列,因为内容是动态的,元素可能非常高/短,所以在左边放5和在右边放5并不总是有效。

4 个答案:

答案 0 :(得分:3)

根据您希望的浏览器支持,CSS列可能是一个解决方案吗?

http://caniuse.com/#feat=multicolumn

body {
    column-count: 2;
}

.element {
    break-inside: avoid;
}

https://jsfiddle.net/erykpiast/fft75mu4/11/

答案 1 :(得分:2)

您可以通过不同方式完成此操作,其中之一(左列 - “floatLeft”类,右列 - “floatRight”类):

.element{width:50%;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;}
.floatLeft{
    float:left;
}
.floatRight{
    float:right;
}
.blue{background-color:#3aa9e3}
.red{background-color:#f15743;}
.green{background-color:#8aba56;}
<div class="element red floatLeft">
    <p>My content goes here! My content goes here! My content goes here! My content goes here!</p>
</div>

<div class="element green floatRight">
    <p>My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here!</p>
</div>
<div class="element blue floatLeft">
    <p>My content goes here! My content goes here! My content goes here! My content goes here!</p>
</div>

答案 2 :(得分:0)

您需要使用javascript。有一个名为masonry(http://masonry.desandro.com/)的轻量级库,可以帮助您实现所需的目标。

答案 3 :(得分:-1)

Ked答案更干净,但你也可以嵌套div标签。像这样:

.element{width:50%;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;}

.blue{background-color:#3aa9e3}
.red{background-color:#f15743;}
.green{background-color:#8aba56;}

.floatLeft{
    float:left;
}
.floatRight{
    float:right;
}
<div class="element floatLeft">
    <div class="red floatLeft"> 
        <p >My content goes here! My content goes here! My content goes here! My content goes here!</p>
    </div>
    <div class="blue floatRight">
        <p>My content goes here! My content goes here! My content goes here! My content goes here!</p>
    </div>
</div>

<div class="element green floatRight">
    <p>My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here!</p>
</div>