My Favorite Ways of Centering With CSS

2 minCSS
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;
}
css

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%);
}
css

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;
}
css

If you know other ways of centering elements, please write a comment below.

Thank you for your time!