Amrin
Posted on January 2, 2022
Centering a div is a crucial skill for a web developer. So, today I’ll share 3 ways to center a div horizontally and vertically.
Let’s get started.
If you prefer video then check it out here:
Note: to center a div with flexbox or grid you need to add flexbox or grid to the parent of that div.
#1. Using Flexbox
You can center a div horizontally and vertically with Flex box, with just 4 lines of code.
div {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#2. Using Grid
Centering a div with grid is much more easier than with flexbox.
div {
display: grid;
place-items: center;
height: 100vh;
}
#3. Using Position Absolute:
You can center a div with CSS positionning too.
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Conclusion
That’s it for today.
If you enjoyed reading this article, I think you’ll also enjoy my newsletter where I share my articles and videos, and other useful resources
Subscribe Now!
Also you can connect with me on Twitter at @coderamrin
Posted on January 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.