CSS float empty spaces

I have several divs in the wrapper, they have different heights. I would like to swim to the left. 2 Divs can fit in a row. But since each div has a different height, a rather strange space remains in the next line. Is it possible to remove the space and move the div up?

Please see the image:

Here is the code:

<div class="wrap">
    <div class="box1">Box1 with less height.</div>
    <div class="box2">Box2 with more height.</div>
    <div class="box3">Box3 with whatever height.</div>
</div>

CSS

.wrap{
    width:410px;
    border:1px solid red;
    overflow:hidden;
}

.box1{
    width:200px;
    height:50px;
    float:left;
    border:1px solid green;
}

.box2{
    width:200px;
    height:150px;
    float:left;
    border:1px solid blue;
}

.box3{
    width:200px;
    height:250px;
    float:left;
    border:1px solid blue;
}

JSFiddle: http://jsfiddle.net/NsH5M/

PS. The height of the div is not fixed. This is just for example. Edit: Sorry, I should have mentioned that it cannot be edited with markup.

enter image description here

+5
source share
7 answers

Try using masonry . This should help you organize your div without empty space.

, : jsfiddle

HTML:

<div class="wrap">
    <div class="box box1">Box1 with less height.</div>
    <div class="box box2">Box2 with more height.</div>
    <div class="box box3">Box3 with whatever height.</div>
</div>

JavaScript:

$(function(){
  $('.wrap').masonry({
      // options
    itemSelector : '.box'
  });
});​

CSS:

.wrap{
    width:410px;
    border:1px solid red;
    overflow:hidden;

}

.box{
    float: left;
    width: 200px;
}

.box1{
    height:50px;
    border:1px solid green;
}

.box2{
    height:150px;
    border:1px solid blue;
}

.box3{
    height:250px;
    border:1px solid blue;
}
+6

float:right .box2 :

.box2{
    width:200px;
    height:150px;
    float:right;
    border:1px solid blue;
}

http://jsfiddle.net/NsH5M/2/

+2

float: , . :

.box2{
width:200px;
height:150px;
float:right;
border:1px solid blue;
}

jsfiddle

+2

, , 1 3 2

EDIT: firefox http://jsfiddle.net/NsH5M/1/

+1

, box1 box3 :

http://jsfiddle.net/NsH5M/3/

: box3, ( , , , .

+1
0

... : " 2 ?". , :

( jQuery, , , , JS)

This is my case class "add-info" has been assigned to all elements in the container. What you are doing is just checking if the next element should move left or right. Do not use complex scripts for everything. Half of the people have access to the network from a mobile phone, and the amount of mobile data is limited.

function contactFloats() {
    var leftCounter = 0;
    var rightCounter = 0;
    $('.add-info').each(function(){
            if(leftCounter <= rightCounter){
                $(this).css('float', 'left');
                leftCounter += $(this).outerHeight();
            }else{
                $(this).css('float', 'right');
                rightCounter += $(this).outerHeight();
            }
    });
}
0
source

All Articles