0
0
CssDebug / FixBeginner · 3 min read

How to Fix Flexbox Items Not Wrapping in CSS

Flexbox items do not wrap because the container's flex-wrap property is set to nowrap by default. To fix this, set flex-wrap: wrap; on the flex container to allow items to move to the next line when needed.
🔍

Why This Happens

By default, a flex container arranges its items in a single line and does not allow them to wrap to the next line. This happens because the flex-wrap property is set to nowrap by default. When items exceed the container's width, they overflow instead of wrapping.

css
div.container {
  display: flex;
  flex-wrap: nowrap; /* default value */
  width: 300px;
  border: 1px solid black;
}

div.item {
  flex: 0 0 150px;
  height: 50px;
  background-color: lightblue;
  margin: 5px;
  text-align: center;
  line-height: 50px;
}
Output
Flex items appear in a single row and overflow the container's width without wrapping.
🔧

The Fix

To fix the issue, change the flex-wrap property to wrap. This tells the flex container to allow items to move to the next line when they don't fit in one row. This keeps the layout neat and responsive.

css
div.container {
  display: flex;
  flex-wrap: wrap; /* allow wrapping */
  width: 300px;
  border: 1px solid black;
}

div.item {
  flex: 0 0 150px;
  height: 50px;
  background-color: lightgreen;
  margin: 5px;
  text-align: center;
  line-height: 50px;
}
Output
Flex items wrap onto multiple lines inside the container, fitting neatly without overflow.
🛡️

Prevention

Always set flex-wrap: wrap; on flex containers when you expect items to flow onto multiple lines. Use responsive widths or flex-basis to control item sizes. Test layouts on different screen sizes to ensure wrapping works as expected.

Using browser DevTools to inspect flex container styles helps catch missing flex-wrap settings early. Consider adding CSS linting rules to warn if flex-wrap is missing when display: flex; is used.

⚠️

Related Errors

Other common flexbox issues include:

  • Items not shrinking: Use flex-shrink or min-width to allow items to shrink.
  • Unexpected spacing: Check margin and gap properties.
  • Vertical alignment problems: Use align-items or align-content to fix.

Key Takeaways

Set flex-wrap: wrap; on the flex container to enable item wrapping.
The default flex-wrap value is nowrap, which prevents wrapping.
Use responsive item widths and test on different screen sizes for best results.
Inspect flex container styles with browser DevTools to debug layout issues.
Consider CSS linting to catch missing flex-wrap settings early.