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.
Top comments (4)
Hey! Pretty cool post!
Just a little tip, you can highlight your code by placing the name of the language after the initial 3 backticks for code blocks, e.g.
```css
/*Your CSS code here*/
```
Hey! Thanks for pointing it out.
You can center a div with absolute position in pure CSS :
Yes we can do that, but this one was more fun 😅, i am learning JavaScript, so i was just experimenting with the possibility.