Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: float blocks to occupy all free space

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;
}
like image 260
cweiske Avatar asked Mar 07 '12 20:03

cweiske


2 Answers

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

like image 113
allaire Avatar answered Oct 03 '22 19:10

allaire


Pure CSS Solution

Tested in Firefox, IE8+ (IE7 looks like it would need to be targeted to add a top margin added to 2.1 because it overlaps 1.1). See fiddle. This assumes .h2 is the middle div (as your example). If left most div it should not need any change. If right most, you would need to expand the negative margin to also include the third div following.

.h2 + div {
    float: right;
    margin: 10px 14px 10px 0; /*14px I believe also has to do with borders */
}

.h2 + div + div {
    margin-left: -434px; /*need to account for borders*/
    clear: right;
}
like image 35
ScottS Avatar answered Oct 03 '22 20:10

ScottS