<tutorialjinni.com/>

Vertically Center Align Text in Div CSS3

Posted Under: CSS3, HTML5, Tutorials on Dec 24, 2016
Vertically Center Align Text in Div CSS3
This tutorial demonstrate how to vertically center or middle align a text in container using pure CSS3. There are many ways but this tutorial explain only two methods that are cross browser and work efficiently in all major browser.

Method 1

First approach is to use CSS3 property Flex
<style>
    #verticalCenterDiv{
        display: flex;
        align-items: center;
    }
</style>
Full working example is
<!DOCTYPE html>
<html>
<head>
    <title>Vertically Center Align Text in Div Using CSS3</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #verticalCenterDiv{

            display: flex;
            align-items: center;     /* Vertical Center Align */
            
            justify-content: center; /* Horizotal Center Align */
            background: linear-gradient(to bottom, #c9de96 0%,#8ab66b 44%,#398235 100%);
            height: 250px;
            color: white;
            font-family:monospace;
            font-size:x-large;
            font-weight: 900;
        }
    </style>
</head>
<body>
    <div id="verticalCenterDiv">
        Vertically Centered Align Text using CSS3
    </div>
</body>
</html>
Browser will render the above code like the below image Vertically Center Align Text using CSS3 Flex

Method 2

This approach emulates the behavior of table in a div. Tables has the ability to center align content in its cells, both vertically and horizontally, for this approach the parent container's display property is set to table and setting the child's display property to table-cell.
<!DOCTYPE html>
<html>
<head>
    <title>Vertically Center Align Text</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #verticalCenterDiv{
        
            display: table;
            
            text-align: center;     /* Vertical Center Align */
            width: 100%;
            height: 250px;
            background: linear-gradient(to bottom, #ffc578 0%,#fb9d23 100%); 
        }
        
        #verticalCenterDiv span{
        
            display: table-cell;
            vertical-align: middle; /* Horizotal Center Align */
                        
            color: white;
            font-family:monospace;
            font-size:x-large;
            font-weight: 900;
        }
    </style>
</head>
<body>
    <div id="verticalCenterDiv">
        <span>
            Vertically Centered Align Text
        </span>
    </div>
</body>
</html>
Chrome Browser render the above code like this Vertically Center Align Text display table


imgae