stevenmc stevenmc - 3 months ago 23
CSS Question

CSS Floating Divs At Variable Heights

I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

enter image description here

I'd really appreciate your help. Thanks :)

<style>
#holder{
width:250px;
border:1px dotted blue;
display:inline-block;
}
.box{
width:100px;
height:150px;
background-color:#CCC;
float:left;
text-align:center;
font-size:45px;
display:inline-block;
}
.one{
background-color:#0F0;
height:200px;
}

.two{
background-color:#0FF;
}

.three{
background-color:#00F;
}

.four{
background-color:#FF0;
}
</style>

<div id="holder">
<div class="box one">1</div>
<div class="box two">2</div>
<div class="box three">3</div>
<div class="box four">4</div>
</div>


Here is the jsfiddle

Answer

To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers):

  • Floats don't work.
  • display: inline-block doesn't work.
  • position: relative with position: absolute requires manual pixel tuning. If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning "automatically" with server-side code.

Instead, use jQuery Masonry.