I\'m trying create a balanced (2-) column-layout.
The content is not text but blocks and varies in height. The content should be placed alternatingly left and right, as
Updated: I believe this is almost impossible to achieve with CSS only. There are many different solutions, but they all require some compromises unless you are willing to use JavaScript or some server-side code.
Here's an alternate fiddle using reordered blocks. Here's a fiddle demo using CSS columns without reordering.
You can use CSS colunms to change your block flow to vertical unless you alter the order of their output. If you can output odd numbers first, then even numbers, you win.
1
3
2
4
.wrapper {
column-count: 2;
column-width: 100px;
-moz-column-width: 100px;
-webkit-column-width: 100px;
width: 260px;
}
div {
border: 1px solid #999;
display: inline-block;
margin: 10px;
width: 100px;
}
.block1 { height: 100px; }
.block2 { height: 130px; }
.block3 { height: 150px; }
.block4 { height: 100px; }
This solution is not compatible with IE9 and below.
If you do know your block heights you can solve this problem by using absolute positioning.
block1 {
height: 100px;
position: absolute;
left: 0;
top: 0;
}
block2 {
height: 110px;
position: absolute;
left: 0;
top: 100px; /* The height of the div above it */
}
A big drawback is dynamic content; we seldom know block height. So this solution is very limited in its application unless you are willing to calculate the height block height.
Use a plugin like Masonry. Both in vanilla js or jQuery flavour.
This leaves you with the following options that require some compromises.
Group your blocks into columns. See this Fiddle for a demo. This will alter the flow of your blocks to vertical, then horizontal.
Use display: inline-block; vertical-align: top;
on your blocks. This will leave some white space below your blocks.
Force the height of your blocks, rendering this a non-issue. For blocks with additional content use the overflow
property to allow in-block scrolling.
As others have commented, you could attempt to calculate the height of the blocks on the server.