This answer has two main sections:
- Understanding how alignment works in CSS Grid.
- Six methods for centering in CSS Grid.
If you're only interested in the solutions, skip the first section.
The Structure and Scope of Grid layout
To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.
The HTML structure of a grid container has three levels:
- the container
- the item
- the content
Each of these levels is independent from the others, in terms of applying grid properties.
The scope of a grid container is limited to a parent-child relationship.
This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.
Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid
feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)
Here's an example of the structure and scope concepts described above.
Imagine a tic-tac-toe-like grid.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
You want the X's and O's centered in each cell.
So you apply the centering at the container level:
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
}
But because of the structure and scope of grid layout, justify-items
on the container centers the grid items, not the content (at least not directly).
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
}
section {
border: 2px solid black;
font-size: 3em;
}
<article>
<section>X</section>
<section>O</section>
<section>X</section>
<section>O</section>
<section>X</section>
<section>O</section>
<section>X</section>
<section>O</section>
<section>X</section>
</article>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…