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.
May be this is what you want:
It's using auto columns instead of template columns.
.grid {
display: grid;
grid-auto-columns: 22%;
grid-gap: 10px;
justify-content: center;
width: 200px;
border: solid 1px black;
grid-auto-flow: column;
}
.item {
height: 50px;
background-color: red;
}
<div class="grid">
<div class="item"></div>
</div>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With