nowrap, the default, keeps every flex item on a single line, shrinking items according to their flex-shrink value if they collectively don't fit, potentially causing overflow if items can't shrink enough. wrap instead allows items to flow onto additional lines once they no longer fit on the current one, similar to how words wrap onto a new line of text, and wrap-reverse does the same but stacks the wrapped lines in reverse order. This is commonly combined with flex-direction: row into the shorthand flex-flow, and is essential for building a responsive grid-like layout of flex items that should reflow onto multiple rows as available space shrinks.
1Understanding Flex-wrap
nowrap, the default, keeps every flex item on a single line, shrinking items according to their flex-shrink value if they collectively don't fit, potentially causing overflow if items can't shrink enough. wrap instead allows items to flow onto additional lines once they no longer fit on the current one, similar to how words wrap onto a new line of text, and wrap-reverse does the same but stacks the wrapped lines in reverse order. This is commonly combined with flex-direction: row into the shorthand flex-flow, and is essential for building a responsive grid-like layout of flex items that should reflow onto multiple rows as available space shrinks.
Set flex-wrap: wrap whenever a row of flex items should be allowed to reflow onto multiple lines on smaller screens, rather than being forced to shrink indefinitely or overflow the container under the default nowrap.
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}2Practical Example
Here is a real-world application of Flex-wrap showing how it is used in production CSS code.
.rigid-row {
display: flex;
flex-wrap: nowrap;
}3Best Practices
Follow these guidelines when working with Flex-wrap:
1. Set flex-wrap: wrap for a responsive row of items, like cards or tags, that should reflow onto additional lines rather than shrinking indefinitely or overflowing on smaller screens
2. Combine flex-wrap: wrap with a gap declaration for consistent spacing between both items and the wrapped lines themselves
3. Remember flex-wrap's default, nowrap, can cause items to overflow their container if they collectively can't shrink enough to fit on a single line
Tip: Set flex-wrap: wrap whenever a row of flex items should be allowed to reflow onto multiple lines on smaller screens, rather than being forced to shrink indefinitely or overflow the container under the default nowrap.
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}