Wrapping and gaps
Definition and purpose
Flex wrapping creates additional flex lines when items cannot fit on one line. Gap adds consistent space between neighboring items and between lines without adding outer margins.
Wrap fixed cards
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; flex-wrap: wrap; gap: 10px; } #p > div { flex: 0 0 140px; height: 30px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>Two cards fit in the first line; the third moves down 40px.
Syntax and mental model
flex-wrap: wrap allows multiple lines; the initial value nowrap keeps one line. In a row flexbox, column-gap separates items within a line and row-gap separates lines. Flex sizing occurs independently per line.
No wrap with fixed basis
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: flex; flex-wrap: nowrap; gap: 10px; } #p > div { flex: 0 0 140px; height: 30px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The third card overflows because shrinking and wrapping are both disabled.
Common mistakes
Wrapping is not a two-dimensional grid. Items in different flex lines need not align into columns. Account for gaps when predicting fit.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Flex containers and axes. Next lesson: Alignment and justification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Wrapping and gaps — knowledge check
Five questions on wrapping and gaps.
What is the initial flex-wrap value?
What does gap add?
How many 140px items fit in 300px with a 10px gap?
Are flex lines sized independently?
What happens when fixed non-shrinking items exceed a nowrap container?