Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

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

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

#container {
  display: grid;
  grid-template-columns: 16.666% 16.666% 16.666% 16.666% 16.666% 16.666%;
}

.item {
  background: teal;
  color: white;
  padding: 20px;
  margin: 10px;
}
<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 class="item">Item</div>
</div>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...