Member-only story
A Masonry layout is a way to fit together elements of possibly different sizes without gaps.
There are many different way to implement masonry layout, using CSS and/or Javascript. It is a kind of bin packing problem.
The method that we will use in this exercise is simple. Adding elements from left to right in a set of columns. Each element is added in the column that has shorter height.
Let’s start digging in the code. We want to transform a list of heights into a two dimensional matrix that represent the columns of the final layout:
So from this data:
items = [ 250, 200, 300, 200, 450, 200, 300, 500, 300, 250, 200, 150, 200 ]
columns = 4
to this matrix:
[ [ (11, 150 ), ( 8, 300 ), ( 5, 200 ), ( 3, 200 ) ] X
, [ ( 7, 500 ), ( 2, 300 ) ] ^
, [ (10, 200 ), ( 4, 450 ), ( 1, 200 ) ] │
, [ (12, 200 ), ( 9, 250 ), ( 6, 300 ), ( 0, 250 ) ] │
]…