How to Fix Flexbox Items Not Wrapping in CSS
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.
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;
}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.
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;
}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-shrinkormin-widthto allow items to shrink. - Unexpected spacing: Check
marginandgapproperties. - Vertical alignment problems: Use
align-itemsoralign-contentto fix.
Key Takeaways
flex-wrap: wrap; on the flex container to enable item wrapping.flex-wrap value is nowrap, which prevents wrapping.flex-wrap settings early.