Dynamic float layout with CSS

Problem

Let me try and explain what I want to achieve. I want X boxes with a specific width (250 px) set but dynamic height to be placed in the body. But I want them to be as compact as possible, no unnecessary empty space between them.

Now If all boxes had same width and height, this would be easy. I could for example just put float:left; on them. But the when the boxes height is dynamic, and all boxes have random height I end up with spaces between the boxes.

Let me show two examples:

This is what I want:

This is what I want

This is what I end up with:

This is what I end up with

This is my CSS:

<style type="text/css">
<!--
body {
background:#CCCCCC;
}
.flowBox {
background:#FFFFFF;
margin:10px;
float:left;
padding:10px;
width:250px;
border:#999999 1px solid;
}
.clear {
clear:both;
}
-->
</style>

HTML example for a box:

<div class="flowBox">
<h1>Header 0</h1>
Erat volutpat. Sed rutr...
</div>

Full source code: http://pastebin.com/UL1Nqyvm

Is there a way to achieve this with CSS? Thanks for any help or directions!

Problem courtesy of: jamietelin

Solution

From what I’ve seen before, what you want to achieve is hardly possible if not impossible with CSS only. What you want, basically, is a layout similar to Pinterest, you can check their website for a reference if you aren’t sure what I am talking about.

From here, you can research a bit more into how Pinterest layout was done and if there are any alternatives — CSS Frameworks, jQuery Plugins and so on.

What I found for you from a short search with having the above in mind:

Additionally, here is a short explanation by Evan Sharp who wrote the code for Pinterest layout:

I wrote the Pinterest script. Here’s the base of how it works:
Beforehand: Absolutely position the pin containers Determine column width Determine margin between columns (the gutter)
Setup an array: Get the width of the parent container; calculate the # of columns that will fit Create an empty array, with a length equaling the # of columns. Use this array to store the height of each column as you build the layout, e.g. the height of column 1 is stored as array[0]
Loop through each pin: Put each pin in the shortest column at the moment it is added “left:” === the column # (index array) times the column width + margin “top:” === The value in the array (height) for the shortest column at that time Finally, add the height of the pin to the column height (array value)
The result is lightweight. In Chrome, laying out a full page of 50+ pins takes <10ms>

You can go from here by either researching into the topic even further with the slight guidance I have provided or if you are into coding, you could even make your own implementation of the above explanation.

It would be much easier to use the jQuery Plugins though, but if they suit your case that’s only for you to decide.

Solution courtesy of: Peter

View additional discussion.