Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center CSS grid when there are less items than columns

Tags:

css

css-grid

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.

like image 824
Ilya Semenov Avatar asked Jun 30 '18 09:06

Ilya Semenov


1 Answers

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>
like image 61
vals Avatar answered Nov 15 '22 04:11

vals