How to vertically and horizontally align flexbox to center ?

As we already know, flexbox is a model and not just a CSS property.

The below image shows a box with two axis, one is Main Axis (i.e. horizontal axis) and Cross Axis (i.e. vertical axis). And for aligning a flexbox in the center, both horizontally and vertically, we are going to need to work on both of this axis.

So, first of all, we need to remember two CSS properties here, and they are:



  • justify-content
  • align-items

The first property, i.e. justify-content, is to align any HTML element on main axis, which is the horizontal axis. And the second property is to align any HTML element on a cross-axis, which is the vertical axis.

So, to align an HTML element in the center of the screen, both horizontally and vertically, we will have to set the value for both of these properties to ‘center’.

Syntax:

.gfg-box {
    display: flex;
    justify-content: center;
    align-items: center;
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <title>Flexbox</title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
  
        .gfg-box {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
        }
  
        .box {
            padding: 8px 35px;
            font-size: 30px;
            color: green;
            border: 10px solid green;
        }
    </style>
</head>
  
<body>
  
    <div class="gfg-box">
        <div class="box">
            <h1>GeeksforGeeks</h1>
        </div>
    </div>
  
</body>
  
</html>

chevron_right


Output:

Note: The ‘height’ property should have the value of ‘100%’ in ‘HTML’, ‘body’ and ‘gfg-box’.

To know more about flexbox and all its properties, refer to this article.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.