I provide this answer because even when there are good ones that provide a solution ( using Freemasonry ) it is still not crystal clear why this cannot be achieved using floats.
(this is important - # 1 ).
An element with a floating point moves as far left or right as it can in the position in which it was originally
So put it like this:
We have 2 div
<div class="div5">div5</div> <div class="div6">div6</div> .div-blue{ width:100px; height:100px; background: blue; } .div-red{ width:50px; height:50px; background: red; }
without float they will be lower than others

If float: right div5 , div6 is on the line where div5 was,
/*the lines are just for illustrate*/

So, if we are now float: left div6 , it will move as far to the left as possible, “ in this line ” (see # 1 above), so if div5 changes its line, div6 will follow it.
Now add another div to the equation
<div class="div4">div4</div> <div class="div5">div5</div> <div class="div6">div6</div> .div-gree{ width:150px; height:150px; background: green; float:right; }
We have it

If we set clear: right to div5 , we force it to take the line below div4

and div6 will float on this new line to the right or left.
Now let’s use as an example the question that brought me here due to duplicating forcing the div stack from left to right
Here is a snippet to test it:
div{ width:24%; margin-right: 1%; float: left; margin-top:5px; color: #fff; font-size: 24px; text-align: center; } .one{ background-color:red; height: 50px; } .two{ background-color:green; height:40px; } .three{ background-color:orange; height:55px; } .four{ background-color:magenta; height:25px; } .five{ background-color:black; height:55px; }
<div class="one">1</div> <div class="two">2</div> <div class="three">3</div> <div class="four">4</div> <div class="five">5</div> <div class="one">1*</div> <div class="three">2*</div> <div class="four">3*</div> <div class="two">4*</div> <div class="five">5*</div>

In the above image, you can see how div.5 is stored next to div.3 , because in its line (given by the field of the line div.4 ), which is as far as possible, div.1* , div.2* , etc. d. also float to the left of div.5 , but since they do not fit on this line, they go to the line below (defined by the line field of div.5 )
Now notice that when we decrease the height of div.2* to be smaller than div.4* , how can it go to div.5* :

Hope this helps to find out why this cannot be achieved with floats. I am only clarifying the use of float (not inline-block) because of the heading “Floating Divs CSS at variable heights”, and because now the answer is rather long.