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

How to display dynamic content in two columns evenly?

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

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

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

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

但在我的例子中,蓝色元素上方有一个空隙,因为右边的元素比第一个左边的元素高。为此推荐的解决方案是什么?我假设这是一个常见问题?

我不想在 CSS 中创建实际的列,因为内容是动态的并且元素可以非常 tall/short,所以说 5 放在左边和 5 放在右边不会'它总是有效。

您可以通过不同的方式完成此操作,其中之一(左栏 - "floatLeft" class,右栏 - "floatRight" class):

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

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

根据您希望的浏览器支持,也许 CSS 列是一种解决方案?

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

body {
    column-count: 2;
}

.element {
    break-inside: avoid;
}

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

Ked Answer 更简洁,但您也可以嵌套 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>