Center a div by using display Flex or Grid
Hi guys, today I would like to share with you a couple of simple ways on how to center a div in a page by using the newest css properties display grid and display flex.
We can achieve the expected result with a few lines of code and we can follow a couple of different approaches:
- The container element set the child element position
- The container element set the display property and the child element set its position
Now we are ready to start but before we do let’s add a class box element in the body of our page
<div class="box"></div>and let’s add some style to the body and to the class box element
body {
background: #2196f3;
}.box {
height: 5rem;
width: 5rem;
border-radius: 1rem;
background: #fff;
}
First Approach
The container element set the child element position
By using display grid we can set the body to display grid then set its min height to 100vh and then we can use the place-content property to center the child element.
The code will look like this:
body {
display: grid;
min-height: 100vh;
place-content: center;
background: #2196f3;
}By using display flex we can use almost the same code but instead of display content we need to use align-items and justify-content.
Get DIVBYDIV’s stories in your inbox
Join Medium for free to get updates from this writer.
The code will look like this
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #2196f3;
}Nice!! now you know a couple of simple ways to center a div in a page.
Let’s take a look of the second approach
Second Approach
The container element set the display property and the child element set its position
By using display grid we can set the grid property in the body and set the place-self one in the element
The code will look like this
body {
display: grid;
min-height: 100vh;
background: #2196f3;
}.box {
height: 5rem;
width: 5rem;
border-radius: 1rem;
background: #fff;
place-self: center;
}
By using display flex we can set the grid property in the body and set the align-self and margin ones in the element
The code will look like this
body {
display: flex;
min-height: 100vh;
background: #2196f3;
}.box {
height: 5rem;
width: 5rem;
border-radius: 1rem;
background: #fff;
margin: 0 auto;
align-self: center;
}
I hope that this article was helpful, have fun and happy coding!








