Menu Close

How to align text vertically/horizontally inside a flexbox using css

flexbox-textalign

Here, we will use flex property to align text vertically and horizontally without any collapse. The flex property is basically added to the css standards for space distribution and element alignment. It is very easy to write, responsive and mobile friendly. The flex property is used to position the child elements within the main container. So the margin doesn’t collapse with the content margins. 

In the below example, we will use the flex property to set the content to vertical and horizontal alignment. By setting the following three properties to the text can be aligned vertically/horizontally. This example also shows how to position the three different directions (center, left and right) of the elements.

  1. align-items
  2. justify-content
  3. Flex-direction

Example

Follow the below example to learn flexbox property.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to align text vertically/horizontally inside a flexbox using css</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        .flex-display{
            display: flex; 
        }
        .flex-box{           
            width: 100%;  
            min-height: 350px; 
            background: #B2BEB5; 
            margin: 20px;
            padding: 20px;
        }
        .text-vertical-center{ 
            display: flex; 
            align-items: center; 
            justify-content: center;
        }
        .text-vertical-left{
            display: flex; 
            align-items: start; 
            justify-content: start;           
        }
        .text-vertical-right{
            display: flex; 
            align-items: end; 
            justify-content: end;            
        }
    </style>
</head>
<body>
    <div class="flex-display">
        <div class="flex-box text-vertical-center"> 
            <div>
                <h2>Example-1</h2> 
                <h3>Align text using Flexbox property</h3> 
            </div>
        </div>
        <div class="flex-box text-vertical-left">
            <div>
                <h2>Example-2</h2> 
                <h3>Align text using Flexbox property</h3>
            </div>
        </div>
        <div class="flex-box text-vertical-right">
            <div>
                <h2>Example-3</h2> 
                <h3>Align text using Flexbox property</h3>
            </div>
        </div>  
    </div> 
</body>
</html> 
Posted in CSS, HTML, Web Technologies

You can also read...