css: float blocks to occupy all free space

cweiske picture cweiske · Mar 7, 2012 · Viewed 15.1k times · Source

I'm trying to make an "image mosaic" that consists mostly of images of the same size, and some of them the double height.

They all should align neatly like this:

goal

To make automatic generation of those mosaic as easy as possible, I thought floating them would be the best option. Unfortunately, the big block causes the following ones to flow behind it, but not before:

current floats

What can I do - apart from manually positioning them - to get the images to the place I want, and still have it easy to automatically create likewise layouts?


The code I'm currently using is :

FIDDLE

HTML :

<div class="frame">
    <div id="p11" class="img">1.1</div>
    <div id="p12" class="img h2">1.2</div>
    <div id="p13" class="img">1.3</div>
    <div id="p21" class="img">2.1</div>
    <div id="p22" class="img">2.2</div>
</div>

CSS :

.frame {
    background-color: blue;
    border: 5px solid black;
    width: 670px;
}
.img {
    width: 200px;
    height: 125px;
    background-color: white;
    border: 1px solid black;
    float: left;
    margin: 10px;
}
.h2 {
    height: 272px;
}

Answer

allaire picture allaire · Mar 7, 2012

You need to use Javascript to achieve this effect, I had to do that once and I used http://masonry.desandro.com/ -- worked well!