Course contentsShow
← Web Development
Lesson 293 of 2,9825. FlexboxFree lesson

Vertical Centering

Master the classic flexbox pattern for perfect vertical and horizontal centering.

Vertical Centering

You'll learn how to perfectly center content both vertically and horizontally using flexbox—solving one of CSS's classic challenges.

For years, vertical centering in CSS was notoriously difficult, requiring hacky workarounds. Flexbox changed everything by making this a simple, elegant task.

The Classic Centering Pattern

The standard flexbox centering technique combines properties you already know:

.container {
  display: flex;
  justify-content: center; /* centers on main axis (horizontal by default) */
  align-items: center;     /* centers on cross axis (vertical by default) */
  height: 400px;           /* container needs a height to center within */
}

With just these three lines, any content inside .container will be perfectly centered both horizontally and vertically.

Why This Works

Think of it like balancing a picture frame both side-to-side and top-to-bottom:

  • justify-content: center handles the main axis (left-right centering in the default row direction)
  • align-items: center handles the cross axis (top-bottom centering)
  • Together, they create that "dead center" effect

Practical Example

.hero {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh; /* full viewport height */
}

This pattern works beautifully for splash screens, hero sections, modal content, or any scenario where you want something precisely centered regardless of screen size.

The container must have a defined height (or min-height) for vertical centering to be visible—without it, the container only grows to fit its content, making centering imperceptible.

Key Takeaway: Perfect vertical and horizontal centering requires just display: flex, justify-content: center, and align-items: center on a container with defined height.