htmlcsscss-grid

CSS Grid that distributes cells evenly in available rows


I am trying to make a CSS grid that distributes cells evenly across available rows so that the last row is not mostly empty. The number of cells is variable and but the cell width is fixed. Container width is also responsive. I can achieve a grid with variable columns/rows with: grid-template-columns: repeat(auto-fill, Xrem);

But when a new row is created there is just one element in it and rest is empty.

See this for example: https://codepen.io/saurabh0/pen/MYgpZWZ

When the 8th element is added I get:enter image description here

This is what I want instead: enter image description here


Solution

  • Since your max value is known you can write specific CSS to cover all the case. The idea is to adjust the number of columns based on the number of elements (I used my online tool to easily get the selectors: https://css-tip.com/quantity-queries/)

    You can easily extend to more than 14 items following the pattern.

    document.querySelector("button").addEventListener('click',function() {
      document.querySelector(".container").appendChild(document.createElement("div")); 
    });
    .container {
      display: grid;
      justify-content: space-between;
      grid-template-columns: repeat(var(--n,1),auto);
      gap: 10px;
      margin: 10px;
    }
    
    .container:has(> :nth-child(2)) {--n:2}
    .container:has(> :nth-child(5)) {--n:3}
    .container:has(> :nth-child(7)) {--n:4}
    .container:has(> :nth-child(9)) {--n:5}
    .container:has(> :nth-child(11)){--n:6}
    .container:has(> :nth-child(13)){--n:7}
    
    
    .container > div {
       height: 50px;
       background: red;
       width: 80px;
    }
    <button>Add</button>
    <div class="container">
      <div></div>
    </div>