Center absolutely positioned elements

Posted on Mar 25, 2025

by Jimmy

CSS

How to position absolutely positioned elements vertically and horizontally.

Center horizontally:

CSS
        
            .element {
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}        
    

Center horizontally and vertically:

CSS
        
            .parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}        
    
For more information, see this stackoverflow post.

Back to Snippets