CSS Center an Element Vertically and Horizontally

Sometimes 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.

Note: I now use Flexbox, see the updated content below.

.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.

updated 05/11/2017

Centering an Element with Flexbox

To center child elements you should apply the following CSS to the parent element.

.container {
    display: flex;
    align-items: center; // vertically align child elements
    justify-content: center; // horizontally align child elements
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 ones. If you would like to hire me, shoot me an email.

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