6

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.

Ilya Semenov
  • 7,266
  • 3
  • 29
  • 28
  • You can't say auto-fit, that will just stretch,and also you can't define a numbered columns count, if so you will have (say 4) columns and when one item is removed it's just the item, the column is still there, you can add one to the columns count, and have the first item start from the second line, which would center it visually, but really it's not – Zohini Jun 30 '18 at 10:48
  • 1
    This is not how Grid layout works. You have 4 columns defined. Your grid items are confined to their assigned column, unless you specify otherwise. https://stackoverflow.com/a/50239093/3597276 – Michael Benjamin Jun 30 '18 at 11:26

1 Answers1

2

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>
vals
  • 58,159
  • 11
  • 81
  • 129