Search code examples
htmlcsscss-grid

Avoid creating empty cells in grid CSS/HTML


Below is more or less what I want but its not perfect: there are gaps in the grid:

Grid with gaps

Is there a way to avoid these gaps? Could this be done with pure CSS? Please find my HTML and CSS below:

HTML:

<div class="image-canvas">
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    <div class='placeholder'></div>
    ...
</div>

CSS:

.image-canvas {
    height: 500px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(0, 80px));
    grid-template-rows: repeat(auto-fill, minmax(80px, 0));
    justify-content: space-evenly;
    grid-gap: 5px;
}

.placeholder:nth-child(3n+2) {
    grid-row: span 2;
    grid-column: span 2;
}

Cheers!


Solution

  • Alright so for anyone wondering in the future, you need to add grid-auto-flow: dense; to the grid container. From:

    .image-canvas {
        height: 500px;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(0, 80px));
        grid-template-rows: repeat(auto-fill, minmax(80px, 0));
        justify-content: space-evenly;
        grid-gap: 5px;
    }
    

    to:

    .image-canvas {
        height: 500px;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(0, 80px));
        grid-template-rows: repeat(auto-fill, minmax(80px, 0));
        justify-content: space-evenly;
        grid-gap: 5px;
        grid-auto-flow: dense; 
    }