How to Use align-content in CSS Grid for Vertical Spacing
align-content property in CSS Grid to control how multiple rows of the grid are spaced vertically within the grid container. It works only when the grid container has extra space in the block (vertical) direction and accepts values like start, end, center, space-between, space-around, and stretch.Syntax
The align-content property sets the vertical alignment of the entire grid content inside the grid container when there is extra space.
start: Aligns grid rows to the top.end: Aligns grid rows to the bottom.center: Centers grid rows vertically.space-between: Evenly distributes rows with first at top and last at bottom.space-around: Evenly distributes rows with equal space around them.stretch: Stretches rows to fill the container vertically (default).
align-content: start | end | center | space-between | space-around | stretch;
Example
This example shows a grid container with three rows and extra vertical space. The align-content property is set to center, so the rows are grouped in the vertical center of the container.
html, body {
height: 100%;
margin: 0;
}
.grid-container {
display: grid;
grid-template-rows: 100px 100px 100px;
height: 400px;
border: 2px solid #333;
align-content: center;
background-color: #f0f0f0;
}
.grid-item {
background-color: #4CAF50;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2rem;
border: 1px solid #333;
}Common Pitfalls
1. align-content only works if the grid container has extra vertical space beyond the total height of its rows. If the rows fill the container exactly, align-content has no visible effect.
2. align-content affects the whole grid's rows, not individual grid items. To align single items, use align-self or align-items.
3. Confusing align-content with justify-content: align-content controls vertical spacing in grids, while justify-content controls horizontal spacing.
/* Wrong: No extra space, so align-content has no effect */ .grid-container { display: grid; grid-template-rows: 100px 100px 100px; height: 300px; /* exactly fits rows */ align-content: center; /* no visible change */ } /* Right: Extra height allows align-content to work */ .grid-container { height: 400px; /* extra space */ align-content: center; /* rows centered vertically */ }
Quick Reference
| Value | Effect |
|---|---|
| start | Align rows to the top of the container |
| end | Align rows to the bottom of the container |
| center | Center rows vertically in the container |
| space-between | Distribute rows evenly, first at top, last at bottom |
| space-around | Distribute rows evenly with equal space around each |
| stretch | Stretch rows to fill the container height (default) |