πŸ”§ Error Fixes
Β· 1 min read

CSS Flexbox Not Centering β€” How to Fix It


Flexbox items not centering

Your flex container isn’t centering items as expected.

Why this happens

Flexbox centering requires two things: the correct alignment properties and a container with explicit dimensions. The most common mistake is using align-items: center for vertical centering without giving the container a height β€” if the container collapses to the height of its content, there’s no extra space to center within. Another frequent issue is confusing justify-content (main axis) with align-items (cross axis).

Fix 1: Center both axes

.container {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
  height: 100vh;           /* needs a height! */
}

Fix 2: The container needs a height

/* ❌ No height β€” nothing to center within */
.container {
  display: flex;
  align-items: center;
}

/* βœ… Give it a height */
.container {
  display: flex;
  align-items: center;
  min-height: 100vh;
}

Fix 3: Use margin auto

.child {
  margin: auto; /* Centers in both directions inside flex */
}

Alternative solutions

Use CSS Grid for simpler centering β€” it requires fewer properties:

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

Prevention

  • Always set an explicit height or min-height on flex containers when you need vertical centering β€” without it, the container shrinks to fit its content and there’s nothing to center within.
  • Remember that justify-content controls the main axis (horizontal by default) and align-items controls the cross axis (vertical by default).

Related: CSS position: sticky Not Working Β· CSS Flexbox & Grid cheat sheet Β· CSS complete guide