CSS Center an Element Vertically and Horizontally

Some times you just need to position something right in the middle. This used to be a tricky endeavor but these days you can just use something as simple as the example below.

This is what I use and it works rather well.

.parent-class {
    position: relative; 
}
.center-absolutely {
    position: absolute;    
    top: 50%;
    left: 50%;        
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

Remember: since this is an absolutely positioned class, you will need to use a relative position parent container to center the element within smaller containers.

In Category: CSS Tips

Matthew Horne

I am a web developer from the United kingdom who taught himself PHP and JavaScript and continues to build on those skills as well as learn new skills.

Show 2 Comments
  • Bican Marian Valeriu 17th June 2016, 1:36 am

    Or you can use flexbox :))

    • Matthew Horne 22nd June 2016, 3:14 pm

      Yes that would be the better more modern approach.

Leave a Comment