How to Use justify-content in CSS Grid Layout
justify-content property on a CSS Grid container to align the entire grid horizontally inside its container. It accepts values like start, end, center, space-between, space-around, and space-evenly to control the horizontal placement of grid tracks.Syntax
The justify-content property in CSS Grid controls the horizontal alignment of the whole grid inside its container. It affects the space between and around the grid tracks (columns).
Common values:
start: Align grid to the left (default).end: Align grid to the right.center: Center the grid horizontally.space-between: Even space between columns, no space at edges.space-around: Even space around columns, edges get half space.space-evenly: Even space between and around columns.
.grid-container {
display: grid;
justify-content: center; /* aligns grid horizontally */
}Example
This example shows a grid container with three columns. The justify-content: center; centers the entire grid horizontally inside the container.
html, body {
height: 100%;
margin: 0;
}
.grid-container {
display: grid;
grid-template-columns: 100px 100px 100px;
justify-content: center;
gap: 10px;
background-color: #f0f0f0;
height: 100vh;
align-items: center;
}
.grid-item {
background-color: #4CAF50;
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100px;
font-size: 1.2rem;
border-radius: 8px;
}Common Pitfalls
1. Using justify-content on grid items instead of the container: justify-content only works on the grid container, not individual grid items.
2. Confusing justify-content with justify-items: justify-content aligns the whole grid horizontally inside the container, while justify-items aligns individual items inside their grid cells.
3. No visible effect if grid width fills container: If the grid columns fill the container width exactly, justify-content has no space to move the grid.
/* Wrong: applying justify-content on grid items */ .grid-item { justify-content: center; /* has no effect here */ } /* Right: apply justify-content on the grid container */ .grid-container { justify-content: center; }
Quick Reference
Summary of justify-content values for CSS Grid:
| Value | Effect |
|---|---|
| start | Align grid to the left edge |
| end | Align grid to the right edge |
| center | Center grid horizontally |
| space-between | Even space between columns, no space at edges |
| space-around | Even space around columns, edges get half space |
| space-evenly | Even space between and around columns |