Topic 43 of 62
Flex Wrapping
Overview
By default, a flex container is stubbornly 1-Dimensional. If you put 10 boxes inside it, it will brutally squish them, or force them to overflow the screen in a single, infinite horizontal line. The flex-wrap property commands the Flex engine to respect the children's widths, and if they run out of horizontal space, physically 'break' the line and wrap the overflowing items down to a newly created row.
Syntax
css
.tag-container {
display: flex;
/* 1. nowrap (Default): Brutally squish items onto one line */
flex-wrap: nowrap;
/* 2. wrap: Allow items to fall to the next row if space runs out */
flex-wrap: wrap;
/* 3. wrap-reverse: Wrap items, but the new rows stack UPWARDS! */
flex-wrap: wrap-reverse;
/* SHORTHAND: flex-flow (Combines direction and wrap) */
flex-flow: row wrap;
}Common Pitfalls
- Forgetting about
align-content. When a flex container wraps and creates multiple rows, how is the empty space between those entire rows handled?align-itemsonly aligns items within a single row. To manage the spacing of multiple wrapped rows on the cross axis, you must usealign-content: center(orspace-between, etc.). - Using
wrapbut failing to give the children amin-widthorflex-basis. If the children have no defined width, the browser will just squish their text until it physically cannot, before it finally decides to wrap them.
Interview Questions
Q:
When
flex-wrap: wrap creates multiple rows, what property controls the spacing/alignment of the entire block of rows?A:
The align-content property. It distributes the extra space on the cross-axis between the newly created flex lines.
Real-World Example
A responsive Tag list (like skills on a resume) that flows naturally.
example
css
.skills-list {
display: flex;
/* Instead of causing horizontal scrolling on a phone,
the tags will just cleanly fall to the next line. */
flex-wrap: wrap;
gap: 8px; /* Standardized spacing between wrapped items */
}Check Your Knowledge
Test your understanding of Flex Wrapping with these quick questions.