DEV Community

Hima varshini Yaleru
Hima varshini Yaleru

Posted on

How to Center a Div Horizontally and Vertically using CSS Flexbox

Introduction

Aligning and centering design elements inside a web page used to require complex CSS hacks, precise pixel margins, or absolute positioning formulas. With the arrival of the CSS Flexbox Layout, centering child elements has become robust, responsive, and requires only three fundamental rules on the parent container.

The Core Principle

To properly align a 'div' using Flexbox, you must activate the layout engine on the parent element (the container holding the item) rather than writing layout instructions on the child element itself.

Key CSS Properties Required

  1. display: flex; — This initializes the flex formatting context for all direct children.
  2. justify-content: center; — This aligns child items precisely in the center along the horizontal main axis.
  3. align-items: center; — This aligns child items perfectly in the center along the vertical cross axis.

Practical Implementation Code

Below is a clean, modern HTML5 and CSS structure you can use to center any element. You can copy and test this directly inside your local VS Code setup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Centering Elements with CSS Flexbox</title>
    <style>
        .flex-parent {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* Fills full viewport height */
            background-color: #f7f9fa;
        }
        .flex-child {
            padding: 30px 50px;
            background-color: #007bff;
            color: #ffffff;
            font-family: Arial, sans-serif;
            border-radius: 6px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>

    <div class="flex-parent">
        <div class="flex-child">Perfectly Centered Content!</div>
    </div>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

  • The container .flex-parent acts as the flex wrapper. Setting its height to 100vh forces the container to occupy the absolute height of the user's viewport screen, making the vertical alignment visible.
  • Once display: flex is parsed by the browser, justify-content shifts the blue inner card to the horizontal middle, while align-items drops it down to the vertical midpoint cleanly.

Top comments (0)