Let's say I have a simple grid which puts items in 4 columns filling the entire container width:
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
justify-content: center;
}
.item {
height: 100px;
background-color: red;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
This works perfectly until I have 3 or less items. They are put into the corresponding cells but as the right cells are empty, visually the grid starts to look "left aligned". This is not cool if the container itself is centered on the page.
How do I center grid when it has 3 or less items? I tried using repeat(auto-fit, 25%) but it doesn't take grid-gap into account. repeat(auto-fit, minmax(25%, 1fr)) stretches content instead of centering it.