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:

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

Dividing Trapezoid Shapes, Cropping Background Images

I am attempting to design a website layout with trapezoid shapes similar to the attached image. Each section should have a background image that fills the background with cover or a similar effect. I successfully created the first section (dark blue) usin ...

Tips for customizing the background color and image of a toaster

Looking to modify the background color and image based on the else condition (toaster.error) success: function (data) { if (data.message != ""){ toastr.success(data.message); ...

Step-by-step guide on replacing a visible div with a new div when a button is clicked

I have organized my website with links on the left sidebar and matching content in the right sidebar, structured within appropriate div elements. My goal is to display only one div at a time when a user clicks on one of the links located on the left side. ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

Can the typical drag and drop cursors be ignored in an HTML drag operation?

I've been working with the HTML drag and drop API to allow users to resize columns in a table. However, I've noticed that when a user starts dragging a column, the cursor changes to one of the default drag and drop effects (such as move or none). ...

Restrict page scrolling to the vertical position of a specified div [Using jQuery, javascript, and HTML]

Currently, I am in the process of developing a personal website that features numerous expandable items. My goal is to restrict the page scrolling to the height of the expanded item once it is opened. I do not want users to be able to scroll above or below ...

Displaying text and concealing image when hovering over a column in an angular2 table

I am currently using a table to showcase a series of items for my data. Each data entry includes an action column with images. I would like to implement a feature where hovering over an image hides the image and reveals text, and vice versa (showing the im ...

Webpage expands its reach beyond the confines of the HTML element

I've recently added a background gradient to my webpage to make it easier on the eyes, but now I've noticed that the page extends past the <html> element and continues scrolling. This also causes the background gradient to repeat below the ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

Update links within a designated div section

How can I change the color and alignment of anchor tags within the third child div that is part of a set of three nested divs? These child divs are arranged side by side within a parent div with the class .logo-bckgrnd-rpt. Although I have successfully tar ...

What is the best way to make sure the background color of a container stretches across the full width of the screen?

I am currently learning HTML and CSS, and as a practice project, I am working on building a portfolio webpage. In the image provided, there are two containers, and I am facing an issue with the space on the sides when changing the background color. Despite ...

Don't forget to keep track of when the user has closed

How can I ensure that the cache retains the user's action of closing the div? Currently, when I close the div and refresh the page, it reverts back to its original state. Is there a way to make this change persistent? Experience it live: Here is the ...

Perform a jQuery computation using a CSS style

Having trouble with a calculation using a CSS property that is not returning any value. Seems like the issue might be due to the CSS property returning '200px' instead of just '200'. Any suggestions for a workaround? Thanks in advance. ...

"Interactive functionality: Toggling checkboxes with a DIV click

I am trying to set up a simple div container that displays contact information in a formatted list (<ul><li>). Clicking on the div currently takes you to the user's profile page, which is functioning correctly. However, I am facing an iss ...

Relative positioning can break the background-clip attribute for text elements

I am experimenting with using background-clip: text on an element that contains some child <p> elements. I wanted to enhance the design by adding some absolutely positioned :after elements to the <p> tags, covering up the text for animation eff ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

The align-middle Bootstrap class does not seem to be working within the specified div

I want to vertically align text (<span class="align-middle">middle</span>) in the center of a div. Here is the code snippet: <div class="col-4 shadow product-added"> <div class="row"> <div cla ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Image with text overlay

In my content, the setup includes the following: <p class="All-Book-Text">Maecenas iaculis, ipsum at tempor placerat, orci ligula aliquam enim, sit amet sagittis turpis enim sit amet lorem. Praesent dapibus pretium felis, et tempus nibh posuere a.&l ...