by Sai gowtham

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course