Search code examples
htmlcsswebcss-gridautofill

How to fill elements automatically with css(css grid)?


How to create this mode automatically with css grid?

Because their number is not known and each time may be different

I want the other ones to fill Josh if the forgiveness was empty (like the picture)

enter image description here

enter image description here

.tests {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}

.tests .test {
    font-weight: 900;
    background-color: rgb(172, 172, 172);
    margin: 3px;
    cursor: pointer;
    border-radius: 10px;
    padding: 5px;
    text-align: center;
}
<div class="tests">
    <span class="test">1</span>
    <span class="test">2</span>
    <span class="test">3</span>
    <span class="test">4</span>
    <span class="test">5</span>
</div>


Solution

  • Solution from here: https://stackoverflow.com/a/56339098/476951

    .tests {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
    }
    
    .tests .test {
        font-weight: 900;
        background-color: rgb(172, 172, 172);
        margin: 3px;
        cursor: pointer;
        border-radius: 10px;
        padding: 5px;
        text-align: center;
    }
    
    .tests > *:nth-child(3n-1):nth-last-of-type(1) {
      grid-column: span 2;
    }
    
    .tests > *:nth-child(3n-2):nth-last-of-type(1) {
      grid-column: span 3;
    }
    <div class="tests">
        <span class="test">1</span>
        <span class="test">2</span>
        <span class="test">3</span>
        <span class="test">4</span>
    </div>
    <br><br>
    <div class="tests">
        <span class="test">1</span>
        <span class="test">2</span>
        <span class="test">3</span>
        <span class="test">4</span>
        <span class="test">5</span>
    </div>
    <br><br>
    <div class="tests">
        <span class="test">1</span>
        <span class="test">2</span>
        <span class="test">3</span>
        <span class="test">4</span>
        <span class="test">5</span>
        <span class="test">6</span>
    </div>