How can I evenly distribute columns in CSS Grid (like space-between in Flexbox)? [duplicate]

1 month ago 64
ARTICLE AD BOX

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>
Read Entire Article