Positioning text at centre of DIV using CSS FLEX BOX METHOD

Posted By : Rohit Goyal | 19-Sep-2016

I'm going to tell you a little bit of things which are still confusing. You often worried about how to Position some text in exact centre of div.

You will try to give margin from top or giving some padding from top but in the end it is hard to place text in exact center.

Sometimes you also use css line-height property and give line height equal to height to div.but this can position only a single line in center of div.

It is wrong method to position text in exact center, instead We can use css flex box method. By this we can easily position text in exact center of

div horizontally and vertically.

HTML:-

           <div id="container">   
                 <div class="box">
                   <p>hello<br/>hy<br/>Bye</p>
                 </div>
               </div>

        

In this there is a parent div name container, inside it there is a child div name box.
We have to position child div in exact center of div.just follow below step

CSS:-

             #container {
                display: flex;              
                flex-direction: column;
                justify-content: center;    
                align-items: center;        
                height: 300px;
                border: 1px solid black;
            }
          
            .box {
                background:#ddd;
                width: 300px;
                margin: 5px;
                text-align: center;
            }  
     

by giving display: flex div behave like a flex. We have to give flex direction:column so that child div behave like column.After that propery  justify-content:center align items vertically and align-items: center align items horizontally.

The Above code tested on firefox version 43 and latest version of google chrome.

That's it.
You'r Done!

THANKS

About Author

Author Image
Rohit Goyal

Rohit is an experienced Frontend Developer, having good experience in HTML5, CSS3, Bootstrap, Jquery, AngularJS, Angular4/5, Restful API Integration, ES6 . His hobbies are playing cards and cricket.

Request for Proposal

Name is required

Comment is required

Sending message..