In your if statement:
if (currentLeft + block.width > containerWidth) {
currentTop += block.height + blockMargin;
currentLeft = 0;
}
you're setting the value of currentTop based on height of the current block that's causing the wrap.
Instead you need to know the max height of the first row's blocks for the x-axis range that the new block is covering. I'm not sureThis pen works for the best way to handle thissecond row of blocks, but I started tinkering with it on Codepen and it might set you in the right direction (I'll come backneeds to updatebe further when I have more time to fiddle withedited so that the 3rd+ row will work - Because the heights of the second row are all unique it) isn't particularly straightforward to calculate the height of the third row.
https://codepen.io/TerabyteTiger/pen/eYXeObp?editors=1011
A lot of what I did could probably be abstracted out into functions, but I wanted to leave it all inline so that it's easier for you to review what I'm doing where. Good luck!