π Introduction
The flex-wrap property controls whether flex items stay on a single line or wrap onto multiple lines. By default, Flexbox tries to fit all items into one row (or column), but withflex-wrap, items can break into new lines when needed. This is extremely useful for building responsive grids, tag lists, cards, and dynamic layouts. π¨β¨
π― What Does flex-wrap Do?
- Controls whether flex items wrap or stay in one line
- Improves responsiveness automatically
- Works together with flex-direction
- Used for grids, layouts, tag systems, and navbars
β¨ Syntax
Syntax
container {
display: flex;
flex-wrap: nowrap | wrap | wrap-reverse;
}π§© Values of flex-wrap
1. nowrap (default)
All flex items stay on a single line. Items shrink if needed, causing them to compress tightly.
nowrap
flex-wrap: nowrap;2. wrap
Items wrap onto multiple lines, from top to bottom (or left to right depending on direction). This is the most commonly used value for responsive layouts.
wrap
flex-wrap: wrap;3. wrap-reverse
Similar to wrap but items wrap in the opposite direction.
wrap-reverse
flex-wrap: wrap-reverse;π₯ Practical Examples
1. Responsive Grid with wrap
Responsive Grid
.container {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.item {
width: 200px;
height: 100px;
background: lightblue;
}2. Tag List that Wraps Automatically
Tag List
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tag {
padding: 6px 12px;
background: #e5e7eb;
border-radius: 20px;
}3. Prevent Wrapping (nowrap)
nowrap Example
.navbar {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
}4. wrap-reverse Example
wrap-reverse Example
.reverse-wrap {
display: flex;
flex-wrap: wrap-reverse;
}π Behavior Comparison
| Value | Description | Use Case |
|---|---|---|
| nowrap | All items stay on one line | Navbars, carousels, horizontal scroll |
| wrap | Items break into new lines normally | Grids, responsive layouts |
| wrap-reverse | Items wrap but in reverse direction | Creative layouts, special UI effects |
π§ Important Notes
- flex-wrap only works on flex containers (display: flex or inline-flex)
- Pair flex-wrap with
flex-basisfor responsive grids - Wrapping does not change the order of flex items unless
orderis used - Combine
flex-wrap: wrap+justify-contentto space items evenly
π Conclusion
The flex-wrap property is essential for creating responsive and flexible layouts. Whether you're building card grids, tag clouds, galleries, or dynamic UI components,flex-wrap: wrap; gives elements the ability to adapt beautifully across screen sizes. Master this property and your Flexbox layouts will feel smooth, natural, and responsive. π