CSS Flexbox is powerful but has several common pitfalls. When flexbox doesn't behave as expected, it's usually because the flex container isn't set up correctly, properties are applied to the wrong element, or there are conflicting styles overriding your flexbox rules.
/* ❌ Problem "” flex on wrong element */
.child { display: flex; justify-content: center; }
/* ✅ Solution "” flex on the container */
.container {
display: flex;
justify-content: center; /* horizontal alignment */
align-items: center; /* vertical alignment */
flex-wrap: wrap; /* allow wrapping */
gap: 16px; /* spacing between items */
}
/* ❌ No height "” nothing to center within */
.container {
display: flex;
align-items: center; /* Has no effect without height! */
}
/* ✅ Set a height for vertical centering to work */
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh; /* Full viewport height */
/* or */
min-height: 300px;
}
/* ❌ Default is nowrap "” items overflow */
.container {
display: flex;
/* flex-wrap defaults to nowrap */
}
.item { width: 200px; } /* Items overflow on small screens */
/* ✅ Enable wrapping */
.container {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.item {
flex: 1 1 200px; /* grow, shrink, basis */
/* Items wrap when they can't fit */
}
/* ❌ flex-direction: column makes items full width */
.container {
display: flex;
flex-direction: column;
align-items: center; /* Needed to prevent full width! */
}
/* Items stretch to full width by default in column direction */
/* ✅ Use align-items to control cross-axis sizing */
.container {
display: flex;
flex-direction: column;
align-items: center; /* Centers items horizontally */
/* or */
align-items: flex-start; /* Left-aligns items */
}
/* ✅ justify-content: space-between needs multiple items */
.container {
display: flex;
justify-content: space-between;
/* Needs at least 2 items to show space between */
}
/* ✅ Use gap for consistent spacing */
.container {
display: flex;
gap: 16px; /* Modern, clean spacing */
}
The container needs a defined height for vertical centering to work. Add height: 100vh, min-height: 300px, or any explicit height to the flex container.
By default, flex-wrap is nowrap. Add flex-wrap: wrap to the container to allow items to wrap to the next line when they don't fit.
justify-content aligns items along the main axis (horizontal by default). align-items aligns items along the cross axis (vertical by default). They swap when flex-direction is column.
In flex-direction: column, items stretch to full width by default. Add align-items: flex-start or align-items: center to the container to prevent this.
In Chrome/Firefox DevTools, inspect a flex container and click the flex badge next to display: flex. This shows a visual overlay of the flex layout with alignment guides.
Explore 500+ free tutorials across 20+ languages and frameworks.