How to Use flex-wrap in CSS: Simple Guide with Examples
Use the
flex-wrap property in CSS to control whether flex items wrap onto multiple lines or stay in a single line inside a flex container. Set it to nowrap (default) to keep items in one line, wrap to allow wrapping, or wrap-reverse to wrap in the opposite direction.Syntax
The flex-wrap property accepts three main values:
nowrap: All flex items stay on one line (default).wrap: Flex items wrap onto multiple lines from top to bottom.wrap-reverse: Flex items wrap onto multiple lines but in reverse order (bottom to top).
css
flex-wrap: nowrap | wrap | wrap-reverse;
Example
This example shows a flex container with multiple colored boxes. Using flex-wrap: wrap; allows the boxes to move to the next line when they don't fit in one row.
css
html, body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.container {
display: flex;
flex-wrap: wrap;
width: 300px;
border: 2px solid #333;
padding: 10px;
gap: 10px;
}
.box {
background-color: #4CAF50;
color: white;
padding: 20px;
flex: 0 0 100px;
text-align: center;
border-radius: 5px;
}
/* HTML structure:
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
</div>
*/Output
A 300px wide box with five green boxes inside arranged in rows. The boxes wrap to the next line after three boxes because they don't fit in one row.
Common Pitfalls
One common mistake is forgetting to set display: flex; on the container before using flex-wrap. Without display: flex;, flex-wrap has no effect.
Another pitfall is using flex-wrap: wrap; but setting fixed widths on flex items that are too wide to fit, causing overflow or unexpected layout.
css
/* Wrong: flex-wrap without flex container */ .container { flex-wrap: wrap; width: 300px; border: 1px solid black; } /* Right: add display flex */ .container { display: flex; flex-wrap: wrap; width: 300px; border: 1px solid black; }
Quick Reference
| Value | Description |
|---|---|
| nowrap | All flex items stay on one line (default) |
| wrap | Flex items wrap onto multiple lines, top to bottom |
| wrap-reverse | Flex items wrap onto multiple lines, bottom to top |
Key Takeaways
Always set
display: flex; on the container before using flex-wrap.flex-wrap: wrap; lets flex items move to new lines when needed.nowrap keeps all items in a single line, which may cause overflow.wrap-reverse wraps items in the opposite direction for special layouts.Use flexible widths on items to avoid overflow when wrapping.