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
heightormin-heighton 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-contentcontrols the main axis (horizontal by default) andalign-itemscontrols the cross axis (vertical by default).
Related: CSS position: sticky Not Working Β· CSS Flexbox & Grid cheat sheet Β· CSS complete guide