Open In App

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

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Centering elements on a webpage is a common task in web development, and CSS Flexbox provides an efficient and straightforward way to achieve this. In this article, we will learn how to center a <div> element both horizontally and vertically using Flexbox.

What is Flexbox?

Flexbox is a CSS layout module designed to make it easy to align and distribute space among items in a container, even when their size is unknown or dynamic. It allows you to create complex layouts with minimal effort, making it a popular choice among web developers.

Centering a <div> Element Horizontally Using Flexbox

To center a <div> element horizontally using Flexbox, follow these steps:

  • Set the Display Property to Flex: First, set the parent container’s display property to flex by adding display: flex;. This enables the Flexbox layout model on the container.
  • Align Items to Center: Use the align-items: center; property to align the items along the cross axis (vertically, in a row layout).
  • Justify Content to Center: Use the justify-content: center; property to align the items along the main axis (horizontally, in a row layout).

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:

Centering a <div> Element Horizontally and Vertically Using Flexbox

To center the <div> element both horizontally and vertically, you need to ensure that the container has a defined height. This can be done by adding height: 500px; or any desired height to the container’s CSS.

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:

Using Flexbox is an effective way to center elements both horizontally and vertically on a webpage. By setting the display property of the parent container to flex and applying justify-content: center; and align-items: center;, you can easily achieve this layout. Flexbox not only simplifies centering but also offers great flexibility and control over the layout of elements on your webpage.



Next Article

Similar Reads