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;
}
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%);
}
-
Here we added
position:absolute
to thecenter-vertical
class so that element breaks out from the normal document flow and positioned to its relative parent. -
The
top:50%
moves the element 50% down of its container height. -
The
translateY(-50%)
moves the element 50% up of its own height.