How to Center a Div Using CSS Grid: Simple Guide
To center a
div using CSS Grid, set the container's display to grid and use place-items: center;. This centers the child div both horizontally and vertically inside the grid container.Syntax
Use the following CSS properties on the container:
display: grid;turns the container into a grid layout.place-items: center;centers the child element horizontally and vertically.
css
.container {
display: grid;
place-items: center;
}Example
This example shows a parent container with a child div centered perfectly in the middle of the page using CSS Grid.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Center Div with CSS Grid</title> <style> body, html { 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; } </style> </head> <body> <div class="container"> <div class="box">Centered</div> </div> </body> </html>
Output
A blue square box with white text 'Centered' is perfectly centered vertically and horizontally on a light gray full screen background.
Common Pitfalls
Common mistakes when centering with CSS Grid include:
- Not setting
display: grid;on the container, soplace-itemshas no effect. - Using
place-contentinstead ofplace-items, which aligns the whole grid area, not individual items. - Forgetting to set a height on the container, so vertical centering doesn't work as expected.
css
/* Wrong: Missing display grid */ .container { place-items: center; /* No effect without display: grid */ height: 100vh; } /* Right: */ .container { display: grid; place-items: center; height: 100vh; }
Quick Reference
Summary tips for centering with CSS Grid:
- Always set
display: grid;on the container. - Use
place-items: center;for simple horizontal and vertical centering. - Ensure the container has a height (like
100vh) for vertical centering. - Use
place-contentonly if you want to align the entire grid area.
Key Takeaways
Set the container's display to grid to enable grid layout.
Use place-items: center to center child elements horizontally and vertically.
Make sure the container has a height for vertical centering to work.
Avoid confusing place-items with place-content; they serve different alignment purposes.
CSS Grid centering is simple and requires minimal code compared to older methods.