How to Center Content Using CSS Grid: Simple Guide
To center content using
CSS Grid, set the container's display to grid and use place-items: center; to center items both horizontally and vertically. Alternatively, use justify-content: center; and align-content: center; for more control.Syntax
Use display: grid; on the container to enable grid layout. Then use place-items: center; to center child elements horizontally and vertically inside the grid container.
Alternatively, use justify-content to center horizontally and align-content to center vertically.
css
.container {
display: grid;
place-items: center;
}Example
This example shows a box centered perfectly in the middle of the page using CSS Grid.
css
html, body {
height: 100%;
margin: 0;
}
.container {
display: grid;
place-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.box {
width: 150px;
height: 150px;
background-color: #4a90e2;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
border-radius: 8px;
}Output
<div class="container"><div class="box">Centered</div></div>
Common Pitfalls
One common mistake is forgetting to set display: grid; on the container, so place-items has no effect. Another is confusing place-items (which centers items inside grid cells) with place-content (which centers the entire grid inside the container).
Also, if the container has no height, vertical centering won't work as expected.
css
/* Wrong: missing display grid */ .container { place-items: center; /* No effect without display: grid */ } /* Right: */ .container { display: grid; place-items: center; height: 100vh; }
Quick Reference
| Property | Purpose | Values for Centering |
|---|---|---|
| display | Defines grid container | grid |
| place-items | Centers items horizontally and vertically | center |
| justify-content | Aligns grid horizontally | center |
| align-content | Aligns grid vertically | center |
| height | Container height needed for vertical centering | e.g., 100vh |
Key Takeaways
Set the container's display to grid to enable grid layout.
Use place-items: center to center children horizontally and vertically.
Ensure the container has height for vertical centering to work.
place-items centers items inside grid cells; place-content centers the entire grid.
Common mistake: forgetting display: grid disables centering properties.