3 simple ways to center a div (or any element) using CSS
Let’s talk about a CSS skill that you will need time and time again: centering an element. At some point, you will need to center a div, a button, an image, a paragraph…the list is endless. So here are a few beginner-friendly ways to do that.
Estimated reading time: 2 minutes
#1: Centering a div with Margin : 0 auto;
In the code sample here, you can see I’ve added margin: 0 auto to the parent element. We are basically saying, “Hey, apply zero margin to the top and bottom of the element but let the super-smart browser calculate the margin for the right and left sides.” This is a really quick way to center an element. You can always adjust the margin for the top and bottom but you will come across and most likely use margin: 0 auto quite a bit.
#2: Centering a div with Flexbox
Don’t get me started on all the ways Flexbox is ahh-mazing. Just test it out for yourself! No really, go test it out… When centering an element with Flexbox, you’ll want to make sure the property display: Flex is on the parent container to indicate that we are creating a flex container. If you forget to add the display: flex property, it will not work. Next, we’ll add justify-content: center: and align-items: center to that same parent container. Justify-content: center will center the elements along the main axis (horizontally). While align-items: center will center the items along the cross axis (vertically). And that’s it! You have a centered element.
For more Flexbox related content, check out 3 things I learned using CSS Grid and Flexbox.
#3: This might be the most beginner-friendly way to center an element: text-align: center.
While this will center text it will also center any inline-block or inline elements in that parent container. So if you add a text-align: center and the element is not moving check to see if it is display:block. And that’s three beginner friendly ways to center elements!
Feel free to fork and test out the code pen. Now go forth and center away….
Looking for more CSS tips and tricks? Checkout how to navigate dev tools to fix CSS issues.
Photo by Helio Dilolwa on Unsplash