Center an Element with Flexbox

Center an element both horizontally and vertically using CSS Flexbox. The simplest and most reliable centering technique in modern CSS.

Basic Layouts

Detailed Explanation

Perfect Centering with Flexbox

Centering an element both horizontally and vertically was historically one of the most frustrating tasks in CSS. Flexbox makes it trivial with just three properties.

CSS Code

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

How It Works

  • display: flex establishes the flex formatting context.
  • justify-content: center centers children along the main axis (horizontally in a row layout).
  • align-items: center centers children along the cross axis (vertically in a row layout).

Together, these two alignment properties create perfect centering in both dimensions. No absolute positioning, no transforms, no table-cell hacks required.

Centering Multiple Items

When centering multiple items, they will be centered as a group:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  min-height: 100vh;
}

The items stay grouped together and the group is centered within the container. Add flex-direction: column to stack and center them vertically.

Alternative: place-items

In modern CSS, you can also center with Grid:

.container {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

However, the Flexbox approach gives you more control when you have multiple items, as you can adjust spacing with gap and direction with flex-direction.

Common Use Cases

  • Login forms centered on the page
  • Loading spinners and progress indicators
  • Hero sections with centered content
  • Modal dialogs
  • Empty state illustrations

Use Case

Use this pattern whenever you need to center content within a container — login pages, loading screens, hero sections, modal dialogs, or any single centered component. It works for both single elements and groups of elements.

Try It — Flexbox Playground

Open full tool