My Favorite Ways of Centering With CSS
Back in the day, I thought centering with CSS was really tricky. Often, I made it much more complicated than necessary. There are many ways to do it depending on the specific situation. Here are my favorite methods for centering both horizontally and vertically.
Position absolute
The first method is absolute positioning. When we know the height and width of the child, we can use margins with a negative value of half the width or height of the child.
.absolute.parent {
position: relative;
}
.absolute .child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -110px;
margin-left: -110px;
}
cssTransform translate
But what if you don't know the height or width? Then, you can use the transform property with a negative translate of 50% in both directions. There you have it!
.translate.parent {
position: relative;
}
.translate .child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
cssFlexbox
Something that I came across later on is the flexbox approach. It's genius! You just need to define two properties with center - which are justify-content
and align-items
. That's it! You could also write flex-end
if you wanted the element at the bottom right corner. Flexbox is actually really fun.
.flexbox.parent {
display: flex;
justify-content: center;
align-items: center;
}
cssDo you know other ways of centering elements that don’t use position absolute, transform translate, or flexbox? I would love to hear about them!
Thank you for your time!