This content originally appeared on DEV Community and was authored by Amrin
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
This content originally appeared on DEV Community and was authored by Amrin
Amrin | Sciencx (2022-01-02T03:51:57+00:00) 3 Ways to center a div horizontally and vertically. Retrieved from https://www.scien.cx/2022/01/02/3-ways-to-center-a-div-horizontally-and-vertically/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.