Emmanuel Akinfulubi

HTML and CSSPractical II

flex-direction, flex-wrap and gap in CSS

17 Direction, wrapping and gap

easy

Lay 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. 1. flex-wrap: wrap is opt-in. The default is nowrap, which shrinks items instead.
  2. 2. flex-direction: column turns the main axis vertical, and wrap then needs a height to wrap against.
  3. 3. gap applies between items only, so there is no leftover margin at the edges to undo.

index.html

<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>

style.css

.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;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
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.

Checks for exercise 17

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.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.