0

I have a container grid to center the child inline-grid element. However, I'm unable to have auto-fill/auto-fit to take as many columns as there can fit. The grid items have a specified width/height.

It is possible to have the inline-grid take as many columns if specified directly, but that is not what I want.

If it's possible doing this with flex it would be okay, even though I prefer using grid.

I want the grid to be CSS ONLY. Do NOT post answers using JavaScript.

body, html {
  margin: 0;
  height: 100%;
}

.container {
  display: grid;
  background: red;
  height: 100%;
}

.grid {
    background: green;
    height: 100%;
    display: inline-grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 100px));
    margin: auto;
}

.item {
  background: blue;
}
<div class="container">
    <div class="grid">
        <div class="item item1"></div>
        <div class="item item2"></div>
        <div class="item item3"></div>
    </div>
</div>
tscpp
  • 1,298
  • 2
  • 12
  • 35

1 Answers1

1

Automatic centering of grid items is not a simple matter because of the column tracks in the container. They restrict movement across the row. The problem is explained in full here:

However, the layout may be possible with flex:

.grid {
  display: flex;
  background: green;
  justify-content: center;
  height: 100vh;
}

.item {
  flex: 0 0 100px;
  background: blue;
}

.item + .item {
  margin-left: 5px;
}

body {
  margin: 0;
}
<div class="grid">
  <div class="item item1"></div>
  <div class="item item2"></div>
  <div class="item item3"></div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701