Cris
Cris

Reputation: 4044

How to float divs with different heights?

What I want to achieve:

enter image description here

What I currently get: (the second box has an extra list item that messes up the whole layout) enter image description here

HTML:

<div id="categories">
    <div class="cat">   cat1    </div>
    <div class="cat">   cat2    </div>
    <div class="cat">   cat3    </div>
    <div class="cat"> cat4 </div>
    <div class="cat">   cat5    </div>
    <div class="cat">   cat6    </div>
    <div class="cat">   cat7    </div>
    <div class="cat">   cat8    </div>
    <div class="cat"> cat9 </div>
    <div class="cat">   cat10   </div>
</div>

One solution would be to group five items in a new div and apply clear:left but I can't do that due to how the php code works.

Upvotes: 3

Views: 14232

Answers (5)

8bitjunkie
8bitjunkie

Reputation: 13245

You may struggle with the height of each container, as it will be set to whatever is inside it. You could grab the elements with something like jQuery to manipulate the DOM for each div container afterwards if height is important and there isn't enough content inside the boxes to stretch them.

As far as horizontal spacing goes, each of these elements could share a CSS class with the same padding?

Block 5 is achievable if each of your containers have explicit widths and the parent container has an explicit width.

Upvotes: 0

mikevoermans
mikevoermans

Reputation: 4007

Not really sure why you can't do the clear left due to how php code works.

<?php
$i = 0;
foreach ( $cats as $cat ) { 
  echo '<div class="cat"> cat '. $i .' </div>';
  if ( $i%5 == 0 ) {
    echo '<div style="clear: left;"></div>';
  }
  $i++
}
?>

Otherwise a non-php solution would be isotope or masonry.

Upvotes: 2

c4urself
c4urself

Reputation: 4287

fiddle http://jsfiddle.net/c4urself/gCEDV/

html

<div id="categories">
    <div class="cat cat1 square">   cat1    </div>
    <div class="cat cat2 square">   cat2    </div>
    <div class="cat cat3 tall">   cat3    </div>
    <div class="cat cat4 square"> cat4 </div>
    <div class="cat cat5 long">   cat5    </div>
    <div class="cat cat6 tall">   cat6    </div>
    <div class="cat cat7 square">   cat7    </div>
</div>

css

body {
    background-color: #ccc;
}
div.cat {
    background-color: #fff;
    float: left;
    margin-left: 5px;
    border: 1px solid green;
    margin-bottom: 5px;
}
#categories {
    width: 230px;
}
.square {
    width: 50px;
    height: 50px;
}
.long {
    width: 100px;
    height: 50px;
}
.tall {
    height: 100px;
    width: 50px;
}

Upvotes: 0

Jon
Jon

Reputation: 1347

I do this a lot, and constantly come back to this reference:

http://css-tricks.com/snippets/css/cross-browser-inline-block/

I think this will help you achieve what you're after.

Upvotes: 11

bc17
bc17

Reputation: 333

Would you not just display all the div's inline-block?

Upvotes: 3

Related Questions