Different ways to center a div


Different ways to center a div demonstrates how we can center a div using different css properties. It discusses use of 'flex box', 'css grid' and a third way which is not very conventional, i.e by using 'position'.
To center a div using Flex.
Centering a div using flex box is really simple. Here is how.
<div class="flex-container">
<div class="item"></div>
</div>
.flex-container {
display: flex;
justify-content: center; //center item horizontally
align-items: center; //center item vertically
height: 100vh;
}
.item {
height: 100px;
width: 100px;
background: black;
}
Note: You need to give the container a height to center the item vertically.
To center a div using Grid.
Centering a div using grid is even simpler. Here is how.
<div class="grid-container">
<div class="item"></div>
</div>
.grid-container {
display: flex;
place-items: center; // center's item horizontally and vertically
height: 100vh;
}
.item {
height: 100px;
width: 100px;
background: black;
}
To center a div using Position.
Centering a div using position is not something you will normally do. Here is how to center a div using position: absolute;
.
<div class="container">
<div class="item"></div>
</div>
.container {
position: relative;
height: 100vh;
}
.item {
position: absolute;
height: 100px;
width: 100px;
background: black;
}
const container = document.querySelector('.container');
const item = document.querySelector('.item');
// clientHeight/clientWidth gives us the height/width of the element in pixels
item.style.top = (container.clientHeight/2) - (item.clientHeight/2) + 'px';
item.style.left = (container.clientWidth/2) - (item.clientWidth/2) + 'px';
Follow me on X to join me in my tech journey.
Subscribe to my newsletter
Read articles from Zaid Hassan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Zaid Hassan
Zaid Hassan
I am a computer nerd who loves to geek out. let's learn things together #learninpublic