Search code examples
csscss-grid

Auto grid sizing allowing nth max in a row in css


I am trying to Auto-Sizing Columns in CSS Grid. Like if I have one child-div it will cover full space in mother-div. But if there are multiple child-div it will allow specific number of child-div in a row . Here I am using CSS grid. But I cant do it. Here is my code

<div class="mother-div">
   <div class="child-div>
   </div>
   <div class="child-div>
   </div>
</div> 

css

.child-div {
    background-color: #257790;
    height: 100px;
    width: 100%;
}

.mother-div {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-gap: 1em;
}

Solution

  • What you are looking is almost automatic, grid will behave like this almost out of the box.

    You only need to set grid-auto-flow to the direction that you want

    To limit the number of items per row, you need to set them to a specific column, using nth-child selector

    this style:

    .child-div:nth-child(5n+1) {
        grid-column: 1;
    }
    

    selects childs for n values 0, 1, 2, and so on, that in the formula 5n+1 gives values 1, 6, 11, 16, ...

    All those children will go to column 1, that matches the requirement for 5 elements per row.

    .child-div {
        background-color: #257790;
        height: 50px;
        width: 100%;
    }
    
    .child-div:nth-child(5n+1) {
        grid-column: 1;
    }
    .child-div:nth-child(5n+2) {
        grid-column: 2;
    }
    .child-div:nth-child(5n+3) {
        grid-column: 3;
    }
    .child-div:nth-child(5n+4) {
        grid-column: 4;
    }
    .child-div:nth-child(5n) {
        grid-column: 5;
    }
    
    .mother-div {
        margin: 10px;
        width: 500px;
        border: solid 3px black;
        display: grid;
        grid-gap: 1em;
        grid-auto-flow: column; 
    }
    <div class="mother-div">
       <div class="child-div">
       </div>
    </div> 
    <div class="mother-div">
       <div class="child-div">
       </div>
       <div class="child-div">
       </div>
    </div>
    <div class="mother-div">
       <div class="child-div">1
       </div>
       <div class="child-div">2
       </div>
       <div class="child-div">3
       </div>
       <div class="child-div">4
       </div>
       <div class="child-div">5
       </div>
       <div class="child-div">6
       </div>
    </div>