CSS- Vertically center text in a div
In this tutorial, we are going to learn about how to vertically center text in a div element using CSS.
Consider, we have the following text in div HTML:
<div class="container">
<h1>Welcome to the blog</h1>
</div>To center a text vertically inside a div, add the display:flex and align-items: center to the div CSS class.
“align-items: center” centers the text vertically.
Here is an example:
<div class="container">
<h1>Welcome to the blog</h1>
</div>CSS:
.container{
display: flex;
align-items: center;
height: 100%;
}or we can add the inline styles to div element using the style attribute in HTML.
<div style="display: flex;justify-content: center; height: 100%;" >
<h1>Welcome to the blog</h1>
</div>Centering the text vertically in div using absolute position
We can use the absolute positioning in css to center the text vertically in a div element.
Here is an example:
<div class="container">
<h1>Welcome to the blog</h1>
</div>.container{
position:absolute;
top:50%;
transform:translateY(-50%);
}-
In the example above we added
position:absoluteto the div element, so the element breaks out from the normal document flow and positioned to its relative parent (eg: body or parent element). -
The
top:50%moves the element 50% down from its position. -
The
translateY(-50%)moves the element 50% up from it’s position.


