Let's say I have a simple grid which puts items in 4 columns filling the entire container width:
.container {
background: lightyellow;
padding: 10px 20%;
text-align: center;
}
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
justify-content: center;
}
.item {
height: 100px;
background-color: red;
}
.container + .container {
margin-top: 30px;
}
<div class="container">
<h1>News</h1>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div class="container">
<h1>News</h1>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
</div>
</div>
As you can see, this works perfectly but only until I have 4 or more items. If I have less items, they are placed 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, as in the example above.
How do I center the 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.