Removing blank spaces using masonry is tricky

Let's assume that you have the following layout:

HTML
<div class = 'Grid'>
    <div id = '1'></div>
    <div id = '2'></div>
    <div id = '3'></div>
    <div id = '4'></div>
    <div id = '5'></div>
    <div id = '6'></div>
    <div id = '7'></div>
    <div id = '8'></div>
    <div id = '9'></div>
</div>

You can create a masonry effect using the following CSS:

CSS
.Grid{
    display: grid;
    grid-template-columns: 33% 33% 33%;
    grid-template-rows: masonry;
}

Let's assume that the blocks has the following heights:

CSS
#1, #4, #7{ height: 100px }
#2, #5, #8{ height: 200px }
#3, #6, #9{ height: 400px }

You'll see something like:

terminal
┌───┬───┬───┐
│ 1 │   │   │
└───│ 2 │   │
    │   │ 3 │
    └───│   │
        │   │
┌───┬───┼───┤
│ 4 │   │   │
└───│ 5 │   │
    │   │ 6 │
    └───│   │
        │   │
┌───┬───┼───┤
│ 7 │   │   │
└───│ 8 │   │
    │   │ 9 │
    └───│   │
        │   │
        │___│

If you try to eliminate the blank spaces by compressing the structure:

terminal
┌───┬───┬───┐
│ 1 │   │   │
└───│ 2 │   │
│ 4 │   │ 3 │
└───└───│   │
│ 7 │   |   │
└───│ 5 |───┤
    │   |  
    └───| 

As you can see, block 4 ends at a lower level than block 3, so it forces block 7 to come before block 5. Thus, if the blocks are sorted by some kind of timestamp, you'll get weird results at this point by using only CSS.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.