Different ways to center a div

thezaidhassan

Zaid Hassan

Posted on January 20, 2024

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>
Enter fullscreen mode Exit fullscreen mode
.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;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
.grid-container {
    display: flex;
    place-items: center; // center's item horizontally and vertically
    height: 100vh;
}
.item {
    height: 100px;
    width: 100px;
    background: black;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
.container {
    position: relative;
    height: 100vh;
}
.item {
    position: absolute;
    height: 100px;
    width: 100px;
    background: black;
}
Enter fullscreen mode Exit fullscreen mode
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';
Enter fullscreen mode Exit fullscreen mode

Follow me on X to join me in my tech journey.

💖 💪 🙅 🚩
thezaidhassan
Zaid Hassan

Posted on January 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Subgrid
undefined Subgrid

November 29, 2024

#CodePenChallenge: Wall of Text
codepen #CodePenChallenge: Wall of Text

November 29, 2024

Body fluids & circulation Task
codepen Body fluids & circulation Task

November 28, 2024

Flip Card on Hover in CSS
codepen Flip Card on Hover in CSS

November 27, 2024

Backlight in CSS
codepen Backlight in CSS

November 27, 2024