Given a collection of boxes of varying height
<div class="collection">
<div style="height:50px">1</div>
<div style="height:80px">2</div>
<div style="height:60px">3</div>
<div style="height:40px">4</div>
<div style="height:80px">5</div>
<div style="height:50px">6</div>
<div style="height:60px">7</div>
<div style="height:40px">8</div>
</div>
and some jquery to give them unique colors (for debugging)
$('.collection>div').each(function (n) {
$(this).css('backgroundColor', 'hsla(60, ' + n*10 + '%, 45%, 1)');
});
How can I display them in "sensible" columns? The best way I can explain it is if there existed a float:up
that would work for boxes with the same width and varying height isomorphically to the way float:left
does for boxes of equal height but varying width.
With float: left
the ordering seems random to the uninitiated, and gives lots of ugly space internally and also to the bottom and right (the padding on .collection
should only be a third of the spacing between boxes):
.collection {
outline: 1px dotted blue;
padding: 5px;
overflow: hidden; /* clearfix */
}
.collection > div {
margin: 0 15px 15px 0;
width: calc((100% - 2 * 15px) / 3); /* doesn't work */
width: calc(33% - 14px); /* magic 14..? */
float: left;
}
https://jsfiddle.net/mojx8rre/1/
I've tried column-count
:
.collection {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
height: 200px;
outline: 1px dotted blue;
padding; 5px;
}
.collection > div {
margin-bottom: 15px;
}
https://jsfiddle.net/25c4g8a8/2/
But that works differently between eg. Chrome and Firefox and the boxes end up sliced - sometimes with just slivers in one column. Chrome:
vs. Firefox: