E-Learning Platform
Web Foundation I

Spacing & Alignment

TeachesThe gap propertyFlex wrap

Your items line up now. Two problems are left: giving them breathing room, and letting them adapt when the shelf runs out of space.

Space between items: gap

You already know margin — space around one box. Spacing every item on a shelf that way means putting a margin on each one, then remembering to skip it on the last item so you don't get an extra gap at the end. gap skips all of that: it's one declaration, on the container, that spaces every item from its neighbor and nothing else:

.tags { display: flex; gap: 12px; }

gap only means something inside a flex (or grid) container — write display: flex first, the same rule from last lesson. One value sets even spacing everywhere; you'll sometimes see two (gap: 8px 16px) for different vertical and horizontal spacing, but a single value covers almost everything you'll build for now.

Letting items wrap: flex-wrap

By default, a flexbox tries to fit every item on one line, squeezing them if it has to — each item gives up a little of its own width so the whole row still fits, which is fine for three nav links and a genuine problem for ten interest tags on a narrow phone screen, where "squeezing" quickly means "unreadable." flex-wrap: wrap changes the rule: once items no longer fit at a reasonable size, the extra ones drop to a new line instead of being crushed —

.tags { display: flex; flex-wrap: wrap; }

— the same way text wraps to a new line instead of running off the edge of the page.

Common mistake

gap looks like it should work on any container, but it does nothing on a plain block-level div — it only applies inside a flex or grid container. If spacing seems to be missing entirely, the first thing to check is whether display: flex made it onto that same element.

Exercise

Space out a row of interest tags

Turn the interest tags below into a flexbox that spaces itself and copes with a narrow screen:

- display: flex; - flex-wrap: wrap; - gap: 12px;