Indrek
Indrek

Reputation: 6696

CSS float causes blank space

I have to show a list of divs in a seamless order, thought their heights may vary. Here's an example: Example divs

As you can see, when an element is floated to the left and is positioned next to another float it generates a white space until the next float. This doesn't happen the other way around. I can't seem to find a way around this and as I use javascript to filter out certain elements (divs) I can not create two different columns.

Here's the html/css:

<div style="width: 200px;">
        <div style="float: left; width: 50%; background-color: green;">
            <p>Float1</p>
        </div>
        <div style="float: left; width: 50%; background-color: blue;">
            <p>Float2</p>
            <p>expanded</p>
        </div>
        <div style="float: left; width: 50%; background-color: yellow;">
            <p>Float3</p>
            <p>expanded</p>
        </div>
        <div style="float: left; width: 50%; background-color: gray;">
            <p>Float4</p>
        </div>
        <div style="float: left; width: 50%; background-color: red;">
            <p>Float5</p>
        </div>
    </div>

Any ideas how to get it to look so that Float1 and Float3 don't have empty room between them?

Upvotes: 3

Views: 6414

Answers (3)

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

appreciate this q is old, for others that find this in a search ( like I was searching ).

the reason for the space is the heights. try setting a height on the floated items.

Upvotes: 2

jeroen
jeroen

Reputation: 91734

In your example it might be possible using float:left for the uneven blocks and float:right for the even ones but in general this is not possible using just css. You will need javascript or 2 separate columns (or a combination...).

As you are using javascript already, it would be pretty easy to load all visible blocks in an array and divide them over two columns.

Upvotes: 3

Calum
Calum

Reputation: 5316

It seems that toggling float:left; and float:right; does what you want: http://jsfiddle.net/cELff/1/

Try using display: inline-block instead of float: left.

Upvotes: 2

Related Questions