Open In App

How to vertically and horizontally align flexbox to center ?

Improve
Improve
Like Article
Like
Save
Share
Report

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 centre, 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 centre 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: 
 

html




<!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>


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.
 



Last Updated : 14 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads