How to center a <div> using Flexbox property of CSS ?
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:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.



