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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…