How to vertically center an element (Css)

How to vertically center an element (Css)

In this tutorial, we are going to learn about two different ways to center an html element vertically with css.

Centering vertically using flex-box

To vertically center elements like (div) we need to add display:flex and align-items:center to the element css class.

Example

Html

<div class="container">
   <p>I'm vertically centered</p>
</div>

Css

.container {
    display:flex;
    align-items:center;
}

css-vertically-center-flexbox

Centering vertically using transform

We can use transform property to absolutely center an element vertically.

Example

<div class="container">
   <div class="center-vertical">
      <p>I'm vertically centered</p>
   </div>
</div>

Css

.container {
 height:200px;
 position: relative;
}

.center-vertical {
 position:absolute;
 top:50%;
 transform:translateY(-50%);
}
  1. Here we added position:absolute to the center-vertical class so that element breaks out from the normal document flow and positioned to its relative parent.
  2. The top:50% moves the element 50% down of its container height.
  3. The translateY(-50%) moves the element 50% up of its own height.