How can I center a div both horizontally and vertically using CSS Grid?
Asked on Sep 06, 2025
Answer
To center a div both horizontally and vertically using CSS Grid, you can utilize the grid's alignment properties. This involves setting the grid container to use `display: grid` and then applying `place-items: center` to center the content.
<!-- BEGIN COPY / PASTE -->
<div class="grid-container">
<div class="centered-div">Centered Content</div>
</div>
<style>
.grid-container {
display: grid;
height: 100vh; /* Full viewport height */
place-items: center; /* Centers the items both horizontally and vertically */
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightblue;
}
</style>
<!-- END COPY / PASTE -->Additional Comment:
- The `place-items: center` shorthand centers items in both directions.
- Ensure the grid container has a defined height, like `100vh`, for vertical centering.
- This method is clean and efficient for centering content with CSS Grid.
Recommended Links: