I've been experimenting with Sveltekit and SCSS to create a Masonry grid. However, I'm facing an issue where the items in my grid are not filling in the empty space as expected. Instead, they seem to be following the size of the largest image, leaving gaps.
While I have successfully implemented a standard CSS grid with 3 columns that looks good, I can't seem to figure out how to make the smaller images fill in the gaps below them. When I inspect the CSS Grid, I notice that the next row of items starts before the previous row ends, instead of merging into it to fill the empty spaces.
I did try using Flexbox as well, but I couldn't quite wrap my head around how to achieve the desired layout. My initial approach was to create three separate flexbox columns, but I feel like CSS Grid would be a better fit for this scenario. However, I am open to any suggestions or thoughts!
In the screenshot provided, you can see the empty spaces in the second and third rows that are being dictated by the size of the first image/card. Grid Screenshot
Below is the HTML markup for the grid and cards:
<div class="gallery-list">
{#if galleryList.length > 0}
{#each galleryList as gallery, index}
<div class="gallery-card">
<div class="gallery-card__image" on:click={() => openGalleryPost(gallery)}>
<img src={gallery.image} alt="">
</div>
<div class="gallery-card__content">
<div class="gallery-card__updates">
<div class="body_11">#{gallery.count}</div>
<div class="body_11 upvotes">
<span class="icon">
<svg width="10" height="11" viewBox="0 0 10 11" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.5625 5.5H8.4375" stroke="#666666" stroke-width="0.75"/>
<path d="M5.625 2.6875L8.4375 5.5L5.625 8.3125" stroke="#666666" stroke-width="0.75"/>
</svg>
</span>
[{gallery.upvotes}]
</div>
</div>
</div>
</div>
{/each}
{/if}
</div>
And here is the SCSS code used for styling the grid and cards:
.gallery-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr auto;
max-height: 620px;
overflow-y: auto;
padding-right: 12px;
gap: 12px;
grid-auto-flow: dense;
.gallery-card {
.gallery-card__image {
margin-bottom: 8px;
cursor: pointer;
img {
width: 100%;
object-fit: cover;
}
}
}
}
If you have any ideas or helpful resources to share, I would greatly appreciate it!