How to float elements with different heights?

Viewed 16413

I'm working on a responsive webdesign that floats multiple items in 4 columns side by side. Those items have different heights and hence floating doesn't properly work.

This is what happens at the moment:

floating wrong

Any ideas on how to make the elements float like that:

floating right

I guess this should work with jQuery "masonry", right? However I'm working with Zepto.js and I guess a jQuery plugin wouldn't work.

Is there any pure CSS (CSS3) way to that? Some trick or so?

If this wouldn't work with pure CSS or with JS is it possible to do this:

floating different

Now the second row with elements 5, 6 and 7 is not "really" floating the way you would expect it but there is a hidden line-break (clearfix) inside.

Is there any way to that with pure CSS? E.g. use nth-child(4n+4) and a pseudo-selector like :after to apply a line-break with content?

Any ideas on that? Any clever tricks to make that work?

8 Answers

I would do it using jQuery like this:

var max_height = divs_cnt = 0;

$("#holder .box").each(function() {
  if (divs_cnt % 4 == 0) {
    $(this).css("clear", "both");
  }
  if (max_height < $(this).height()) {
    $("#holder .box").height($(this).height());
  }
  max_height = $(this).height();
  divs_cnt ++;
})
#holder{
   width:100%;
   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;
}

.five{
   background-color:#0a1;
}

.six{
   background-color:#ec5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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 class="box five">5</div>
    <div class="box six">6</div>
</div>

Related