Skip to content
Related Articles

Related Articles

How to vertically and horizontally align flexbox to center ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 14 May, 2021

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’.

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



<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
        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;
    <div class="gfg-box">
        <div class="box">


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
Recommended Articles
Page :

Start Your Coding Journey Now!