Just The Code Please

How to center an element using CSS Grid

January 9th 2024

Summary

A more recent addition to our CSS toolbox has been a technology called CSS Grid. It has many uses and it's designed to help us precisely position elements on a webpage. This can help a great deal when it comes to centering elements. Here is how we can use CSS Grid to center things.

The Code

Center Elements Horizontally

The centering behavior is applied to all child elements

CSS
.container {
    display: grid;
    justify-items: center;
}

Center Elements Vertically

The centering behavior is applied to all child elements

CSS
.container {
    display: grid;
    align-items: center;
}

Center an Element Horizontally and Vertically

CSS
.container {
    display: grid;
}

.item {
    place-self: center;
}
HTML
<div class="container">
    <div class="item"></div>
</div>

Horizontally and Vertically Center Elements (Alternative)

This alternative applies horizontal and vertical centering to all children. It is shorthand for justify-content and align-items.

CSS
.container {
    display: grid;
    place-items: center;
}

Related Links