Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS float empty spaces [duplicate]

Tags:

html

css

I have multiple divs in a wrap, they have different height. I'd like to float left. 2 Divs can fit in a row. But since each of the div has different height, there's pretty much odd space left in next row. Can I remove the space and move the div's up?

Please look at the image:

Here's 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 div heights are not fixed. This is just for example. Edit: Sorry, I should have mentioned that its not possible to edit markup.

enter image description here

like image 741
user1355300 Avatar asked Jun 21 '12 10:06

user1355300


2 Answers

Try to use masonry. This should help you to arrange your div without empty space.

That's how it is used as an example of your code: jsfiddle (Updated 11/2018)

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'
  });
});​
​

And 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;
}
like image 128
Xella Avatar answered Nov 08 '22 08:11

Xella


Just use float:right for the elements that you want on the right. In this case:

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

Your jsfiddle updated here

like image 33
Rorok_89 Avatar answered Nov 08 '22 06:11

Rorok_89