How to center elements on the last row in CSS Grid?

fightstarr20 picture fightstarr20 · Sep 18, 2017 · Viewed 18.2k times · Source

I am using CSS grid to layout some items like this...

How can I get the last row to be centered instead of left aligned? I can't guarantee the number of items so want to make the layout look right for any number of items.

Is this something I should be using flexbox for instead? Or are CSS grids a suitable use?

Answer

Michael Benjamin picture Michael Benjamin · Sep 18, 2017

CSS Grid isn't suited for alignment across an entire row because of crisscrossing tracks blocking the way. Here's a detailed explanation:

As an alternative, use flexbox with justify-content: center.

This packs all items in the horizontal center of the row. Then your margins push them apart.

On fully-filled rows, justify-content will have no effect since there's no free space for it to work.

On rows with free space (in your case, only the last row), the items are centered.

#container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  flex: 0 0 calc(16.66% - 20px);
  background: teal;
  color: white;
  padding: 20px;
  margin: 10px;
}

* {
  box-sizing: border-box;
}
<div id="container">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>