CSS Center an Element Vertically and Horizontally

CSS Tips

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.

[thesis_block type=”note” header=”” content=”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/2022

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
Matthew Horne

Matthew is a web developer from the United Kingdom who taught himself PHP and JavaScript and never looked back. If you would like to hire me, shoot me an email.