An Interest In:
Web News this Week
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
- March 13, 2024
January 2, 2022 03:51 am GMT
Original Link: https://dev.to/coderamrin/3-ways-to-center-a-div-horizontally-and-vertically-220n
3 Ways to center a div horizontally and vertically
Centering a div is a crucial skill for a web developer. So, today Ill share 3 ways to center a div horizontally and vertically.
Lets 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
Thats it for today.
If you enjoyed reading this article, I think youll 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
Original Link: https://dev.to/coderamrin/3-ways-to-center-a-div-horizontally-and-vertically-220n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To