Center Grid Cells on Page
How does one keep the grid cells centered on the page?
If your grid content matches your grid cell width, no problem. But there are other scenarios; Here's one: The grid is full container width, but the content floats in the middle, not stretching to the width of the cell.
2 Columns
If we have two columns, the columns being wider than the content, but wanting the content to be centered on the page, the layout might look like this:
.grid
┌───────────────────────┐ ┌───────────────────────┐
│ .cell │ │ │
│ ┌────────────┐ │ │ ┌────────────┐ │
│ │ .content │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ └────────────┘ │ │ └────────────┘ │
│ │ │ │
└───────────────────────┘ └───────────────────────┘
┌───────────────────────┐ ┌───────────────────────┐
│ │ │ │
│ ┌────────────┐ │ │ ┌────────────┐ │
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ └────────────┘ │ │ └────────────┘ │
│ │ │ │
└───────────────────────┘ └───────────────────────┘
Use justify-items: left
to put content on the left of the grid by default. Then target the odd-numbered cells to justify-self: right
:
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
justify-items: left;
}
.grid > *:nth-child(2n + 1) {
justify-self: right;
}
If you're looking for the same in Tailwind (because all Tailwind devs keep a docs tab open, right), you can with Tailwind 3.1+, which allows arbitrary variants:
<div class="grid grid-cols-2 [&>*:nth-child(2n+1)]:justify-self-end justify-items-start" />
Still another alternative: If your generating code in a loop, you could add a class to justify-self
on every nth element.
3 Columns
What about a 3-column layout. Still doable? It looks like this:
.grid
┌───────────────────────┐ ┌────────────────┐ ┌───────────────────────┐
│ .cell │ │ │ │ │
│ ┌────────────┐ │ │ ┌────────────┐ │ │ ┌────────────┐ │
│ │ .content │ │ │ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │ │ │ │ │
│ └────────────┘ │ │ └────────────┘ │ │ └────────────┘ │
│ │ │ │ │ │
└───────────────────────┘ └────────────────┘ └───────────────────────┘
And change your styles. The nth-child
formula will change. The inner column will have an auto
width:
.grid {
display: grid;
grid-template-columns: 1fr auto 1fr;
justify-items: left;
}
.grid > *:nth-child(3n + 1) {
justify-self: right;
}
To see these grids in action, check out the codesandbox.
Well, there's a way to center 'em. Any alternate methods you prefer?