flex-direction, flex-wrap and gap in CSS
17 Direction, wrapping and gap
easyLay items in a row that wraps onto more lines when it runs out of room, then stack the same items in a column. Space them with gap rather than margins.
Stuck? Three hints, smallest first
- 1.
flex-wrap: wrapis opt-in. The default isnowrap, which shrinks items instead. - 2.
flex-direction: columnturns the main axis vertical, andwrapthen needs a height to wrap against. - 3.
gapapplies between items only, so there is no leftover margin at the edges to undo.
<ul class="row">
<li>Abuja</li>
<li>Kano</li>
<li>Enugu</li>
<li>Ibadan</li>
<li>Benin</li>
<li>Warri</li>
<li>Jos</li>
</ul>
<ul class="col">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
.row, .col {
list-style: none;
margin: 0 0 12px;
padding: 0;
display: flex;
gap: 8px; /* between items only, never at the edges */
}
.row {
flex-wrap: wrap; /* opt-in: the default is nowrap */
}
.col {
flex-direction: column;
align-items: flex-start; /* otherwise each item stretches full width */
}
.row li, .col li {
padding: 7px 12px;
background: #eef1fd;
border: 1px solid #3055d8;
border-radius: 999px;
font-size: 0.85rem;
}
7 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('both lists are flex containers', (css.match(/display:\s*flex/g) || []).length, 1);
test('the row wraps', /flex-wrap:\s*wrap/.test(css), true);
test('the column runs down the page', /flex-direction:\s*column/.test(css), true);
test('spacing is gap, not margins on the items', /gap:\s*8px/.test(css), true);
test('and the items carry no margin of their own', /li\s*\{[^}]*margin/.test(css), false);
test('the column items do not stretch to full width', /align-items:\s*flex-start/.test(css), true);
test('seven items in the row, three in the column', countTag(html, 'li'), 10);
Output
Two defaults catch people out. flex-wrap is nowrap unless you say otherwise, so an overfull row squeezes its items down to nothing rather than moving them to a second line. And align-items defaults to stretch, so items in a column go full width unless you say flex-start — which is usually read as “my width is being ignored”. gap is strictly better than margins here: it only ever applies between items, so there is no trailing margin on the last one to strip off with :last-child.