3 easy ways to Center Anything with CSS

< 1 min read

In this tutorial, we'll go over how to center different elements both vertically and horizontally.

1) Center a Div Vertically with Transform and Translate

For this example, we will create 2 div's
On the container class, we will assign it a position of relative. On the child class, we will assign it a position of absolute and set top and left to 50%. Now to center the child class, just use transform: translate(-50%, -50%);

<div class="container">
  <div class="child"></div>
</div>
.container{
  position: relative;
}
.child{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

2) Center a Div using flexbox

Using transforms you get the job done, however usig flexbox you can do it easily.
To center an element, apply display: flex and align-items: center and justify-content: center to the container class.

<div class="container">
  <div class="child"></div>
</div>
.container{
  display: flex;
  justify-content: center;
  align-center: center;
}

3) Center a Div using a grid

Let's take it a step ahead, using CSS GRID we can achieve the same using 2 lines of CSS.
To center an element, apply display: grid and place-items: center to the container class, that's it.

<div class="container">
  <div class="child"></div>
</div>
.container{
  display: grid;
  place-items: center;
}

Join my mailing list

You will receive weekly updates on  exciting articles such as this straight in your inbox.
P.S I promise not to be a human spam.