How to Center a Div with Flex box and CSS Grid

How to Center a Div with Flex box and CSS Grid

Centering a div is one of the things that developers who just started learning/using CSS struggled with. I also had the same problem when I was learning CSS, not until I google it that I realise how easy it is to center a div.

We will be looking at how to center a div with Flexbox and CSS Grid

This is our HTML code:

<div class="parent-div">
    <div class="child-div"></div>
</div>

And our CSS code:

.parent-div{
    background-color:blue;
}
.child-div{
    width:200px;
    height:200px;
    background-color:black;
}

This is how our page looks at the moment:

Centering A Div With Flexbox

.parent-div{
    background-color:blue;
    display:flex;
    justify-content:center;
    align-items:center;
}
.child-div{
    width:200px;
    height:200px;
    background-color:black;
}

This is what we will get from the above code:

You are probably thinking this is not centered but I can assure you it is, the problem with this is that we haven't set the height of the parent div, so by default the height of the parent div is the same as the child div. now see what happens when I give the parent div a specific height

.parent-div{
    background-color:blue;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
}
.child-div{
    width:200px;
    height:200px;
    background-color:black;
}

This will be our result:

With this, we have successfully centered a div using Flexbox.

Centering A Div With CSS Grid

Centering a div with CSS Grid is similar to the way we center a div with flexbox but there is a minor difference which is instead of using justify-content and align-items, we use place-content. place-holder will center the div vertically and horizontally.

Note: Remember to add the height property in the parent div and give it an appropriate value

.parent-div{
    background-color:blue;
    display:grid;
    place-content:center;
    height:100vh;
}
.child-div{
    width:200px;
    height:200px;
    background-color:black;
}

This will be our result:

With this, we have successfully centered a div using CSS Grid.

Conclusion

There is more than one way to center a div with flexbox or CSS Grid but I think the above method is the simplest. I hope you find this blog useful.