Skip to content
Related Articles

Related Articles

How to center a <div> using Flexbox property of CSS ?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 25 Jun, 2021
View Discussion
Improve Article
Save Article

In this article, we will learn to center an HTML div element using flexbox property of CSS. 

Please refer this article to know more about flexbox.

Approach: To center the <div> element horizontally using flexbox.

  • We use the property of display set to flex i.e. display: flex;
  • Align items to center using align-items: center;
  • The last step is to set justify-content to center i.e. justify-content: center;

Example 1: The following example is using flex property.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .center {
            display: flex;
            justify-content: center;
            color: green;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <div class='center'>
        This text is centered
    </div>
</body>
  
</html>


 

Output:

Example 2: If we want to center the <div> horizontally and vertically, we just add height: 500px; in the CSS part of the code.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .center {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 500px;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <div class="center">
        This text is centered
    </div>
</body>
  
</html>

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!