-
Notifications
You must be signed in to change notification settings - Fork 0
Creating a Masonry Display
Unlike fixed grid layouts, a masonry grid display reduces any whitespace between items by placing each item one after the other and is commonly implemented in gallery websites like Unsplash and Pinterest. This layout is best achieved in CSS using columns; however, this causes items to be rendered in vertical order rather than horizontally based on ordered search results. Flexbox and grid accounts for this issue but only suit items of fixed/known heights.
The current workaround is to reorder the items retrieved from the database in a way that will cause the columns layout to order them horizontally.
When media items are retrieved from the database, they are added in order to an array/map. For example, let a collection of item IDs retrieved be [1 2 3 4 5 6 7 8].
For a masonry grid with 3 columns, this will render a grid layout with the items in vertical order:
1 4 7
2 5 8
3 6
Items are required to be displayed in the following order instead:
1 2 3
4 5 6
7 8
We essentially require the array of items to be transformed from [1 2 3 4 5 6 7 8] to [1 4 7 2 5 8 3 6]. Notice a pattern between the two layouts. At each column, the next item is the item at an index current_index + number_of_columns. In the first column, we get the item at index 1, the next item at index 1+3=4, the next item at index 4+3=7. We break to the next column when the index exceeds the size of the array.
We have two ‘pointers’: one points to the column, and the other points to the element that is number_of_columns units apart to push to an array.
A pseudocode of the implementation is given below.
from column 1 to n
index = column
while the index does not exceed size of array
get ID at this index
push the ID
index = index + number of columns
end
if the index exceeds size of array
let prevID be ID of previous index
assign a break-column-after property to the div with this ID
end
end