My Favorite Ways of Centering With CSS
Back in the day, I thought that centering with CSS was really tricky. Often, I made it much more complicated than it is. There are many ways to do it depending on the specific situation. These are my favorite ways of centering both horizontally and vertically.
Position absolute
The first method or approach is the absolute positioning. We know the height and width of the child and we can then 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;
}
Transform 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%);
}
Flexbox
Something that I came across later on is the flexbox approach. It's genius! You just need to define two properties with center - which is 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 really fun.
.flexbox.parent {
display: flex;
justify-content: center;
align-items: center;
}
If you know other ways of centering elements, please write a comment below.
Do you use another approach? 🤔
Do you use Sass mixins or other cool things? 🤔
Thank you for your time!
If you liked this, then please ❤️ and follow me on Twitter.
Top comments (2)
This is just another way to achieve the first method, just without the negative margins.
You are absolutely right 😊 But I'm so happy, that flexbox is well supported in these days. It is so much easier and looks much more clean.