The Masonry Grid is leaving empty spaces unfilled

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!

Answer №1

For achieving equal heights, consider using the following declaration:

grid-auto-rows: 1fr;

If aligning images with content is necessary, it might be helpful to restructure the layout. Consider nesting elements like this: https://i.sstatic.net/xV4xFCvi.png

Once you've restructured the layout and nested accordingly, you can use the line mentioned earlier to ensure equal box heights. If alignment within the parent container is needed, utilize align-self under gallery-card__content.

Alternatively, ensuring that all images have the same dimensions could also solve the issue. The aspect-ratio property in CSS allows setting specific ratios, while object-fit: cover ensures images scale appropriately inside their containers - especially useful for similar yet not exact ratios.

.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;
        grid-auto-rows:1fr;

        .gallery-card {
          .gallery-card__image {
            margin-bottom: 8px;
            cursor: pointer;
            img {
              width: 100%;
              // height: 100%;
              object-fit: cover;
            }
          }
        }
  .gallery-card {
    border: 1px solid #000;
  }
  .gallery-card__content {
    
  }
}
<div class="gallery-list">
   ... (Images and Content sections) ...
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Another element concealing an element underneath

I am currently working on a website and could really use some assistance. Being new to web design, I find myself puzzled by this particular issue. The problem I'm facing is with a sawtooth pattern that should be displayed over a header, similar to the ...

Is there a way to reverse the hover effect on div elements?

Let's start by examining the code I've written: HTML: <div class="button_container"> <div class="inner_button"> <a href="#" class="button_text">Button</a> </div> <div class="button_side"> ...

How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again. View the DEMO here. Challenge Description:- I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the ...

Rearranging the Foundation Grid by incorporating smaller panels ahead of larger panels

I am in the process of designing a visually appealing webpage with no text other than captions. To achieve the desired look, I aim to have each clickable box display in a unique size. Here is the layout I envision: __________________________ | ...

What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element However, when I try to implement it in the code below, the background color ends up being transparent: { modules.map((module, index) => ( <div className='carou ...

Determine the vertical distance that a div element is currently visible while scrolling

To better understand this concept, please refer to the following fiddle: http://jsfiddle.net/abhicodes/LasxP/ The main goal here is to calculate the visible height of the element with the ID #content-wrapper as the user scrolls. The height of the header ( ...

Red-colored text (as displayed in Firefox) is not recognized by JSoup when parsing HTML <img> tags

UPDATE: I was able to answer my own question. JSoup can indeed find all image tags. I've been attempting to scrape content from but encountered a problem. In the website's source code, the main images are displayed in red font, which seems to ...

What is the best way to create vertical separators between CSS grid elements?

I currently have a grid with 3 columns and would like to add two vertical lines to separate the elements. To achieve this, I have placed two span elements between the grid elements using css styling. .vertical_line { position: absolute; height: 100%; ...

What is the best way to align a button with the edge of an image?

How can I use CSS to position a button on the edge of an image? https://i.stack.imgur.com/FEFDC.png Here is my code: <div> <button class="" aria-label="Eat cake">Btn</button> <img class="pull-left" src="style.png" style="widt ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Inline styles are effective, but external stylesheets are not functioning properly (see JsFiddle for reference)

http://jsfiddle.net/xw0vvo9e/4/ Trying to specify a background color for the navBar. In the provided jsfiddle, the CSS includes: div .navBar { width: 100%; height: 45px; background-color: #FF0000; top: 0px; position: fixed; } However, the background ...

Achieving and maintaining the center alignment of a horizontal dropdown menu

Struggling with creating a fixed, 100% width nav bar that stays centered when the page is resized? The drop down menu headings are causing issues as they seem to float left instead of staying centered. Not sure how to fix it? Take a look at the live resul ...

Troubleshooting: Datepicker not appearing in Bootstrap

Here is the detailed markup for the datepicker component: <div class="form-group row"> <div class="col-xs-3 col-md-offset-9"> <label class="control-label">Pick Date</label> <div class="input-group date" id="dp3" data-d ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...

Ways to eliminate the default underline in MUI typography

I have a unique Moviecard component in my React app that I built with MUI. It has this persistent and bothersome underline on every Typography component, and no matter what I try, like setting textDecoration to none, it just won't go away. There seem ...

Is there a way to insert a record upon the user clicking on the Add Record button?

// Here is my Component code // I want to figure out how to add a new row to the table with fresh values. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-uom', templateUrl: './uom.component.html ...

What are the steps to make a dropdown menu using only HTML and CSS?

Can someone please share the most straightforward method for creating a drop-down list using just HTML and CSS? ...

Is it frowned upon or considered incorrect to achieve a horizontally centered page by adjusting the CSS properties of the html tag?

Is it considered wrong or frowned upon to center a webpage horizontally by adjusting CSS properties of the HTML tag? Sample CSS code: <style type="text/css"> html { width: 1200px; margin: 0px auto; background-color: ...

Can someone guide me on how to align text to the bottom border of a page?

Is there a way to adjust the position of the header text ("bottom text") so that it appears just above the bottom border of the page? I have attempted modifying styles and classes within the footer, style, and h3 tags but have not had any success. Below ...

I'm facing an issue where I am unable to install packages using npm due to an ERESOLVE

Every time I attempt to add an NPM package, a recurring error message appears: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @supabase/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...