Profile Picture
Heru Hermawan
Open menu

CSS Grid to center vertical and horizontal

27/4/2022

––– views

CSS Grid to center vertical and horizontal

As a follow-up to the CSS Flex center article, it's time to show you another view of the same principle. We'll use CSS Grid to center horizontally and vertically in this tutorial.

CSS Grid, like Flexbox, makes it simple to center an HTML element.

With CSS grid, all we need is the following CSS code to completely center an item:

CSS
.container {
display: grid;
place-items: center;
min-height: 100vh; /* optional */
}

The min-height property is optional. In this case, it's needed to give the HTML canvas a vertical height.

The following CodePen example shows how to use the above code to align an item horizontally and vertically using CSS grid:

CSS Grid center horizontally

If you only want to center an element horizontally, for example, you can use the CSS grid code:

CSS
.container {
display: grid;
justify-content: center;
min-height: 100vh;
}

To make it horizontally centered, we can use the justify-content property and pass the center value to make it horizontally centered.

Note: this is the same as for display: flex.

This code results in the following Codepen:

CSS Grid center vertically

On the other hand, maybe all you want to do is vertically center an item.

To achieve this in CSS grid, use the following code:

CSS
.container {
display: grid;
align-items: center;
min-height: 100vh;
}

To achieve vertical alignment on the item, we use align-items with a value of center.

Note: This is also the same functionality that we saw in CSS Flex tutorial.

See the following Codepen for an example:

That's it! Using CSS Grid, we can now center elements horizontally, vertically, or both. 😉

Happy coding!

Thank you for reading 🙏. Feel free to share and/or react!


Article Reactions

👍
❤️
👏
🎉
💯

Share Article


More articles

If you enjoyed this article, you'll find these insightful too!

Introduction to Networking - Interfaces and Protocols

Introduction to Networking - Interfaces and Protocols

16/5/2022 Read

A list of some common and basic networking interfaces and protocols.

CSS Flexbox to center vertical and horizontal

CSS Flexbox to center vertical and horizontal

13/4/2022 Read

How to center an element vertical and horizontal using flexbox css.

Introduction to Networking - Terminologies

Introduction to Networking - Terminologies

9/5/2022 Read

A list of some common and basic networking terminologies.