E-Learning Platform
Web Foundation I

Flexbox Layout

TeachesFlexbox containersFlexbox alignment

Your boxes look right on their own. Now let's line more than one of them up at once.

Turning a container into a flexbox

Picture a shelf. Whatever you put on it lines up along its length automatically — you don't measure gaps by hand. display: flex turns any container into that shelf: everything directly inside it becomes a flex item, and the browser lines those items up in a row, on its own.

.nav { display: flex; }

That one declaration is doing real work. Left alone, three a elements just flow like text — wrapping onto a new line the moment they run out of room, the same as words in a paragraph. Wrap them in a flexbox and they behave like real shelf items instead: a predictable row, ready for the alignment properties below. Want a vertical shelf instead of a horizontal one? Add flex-direction:

.gear-list { display: flex; flex-direction: column; }

Positioning items: justify-content and align-items

Once a container is a shelf, two more properties decide exactly where items sit on it. justify-content spreads items along the shelf's own direction — the main axis (a row, by default). align-items positions them across the other direction — the cross axis, perpendicular to the shelf:

.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

space-between pushes the first item to one end, the last to the other, and spreads the rest evenly between them. center lines every item up in the middle of the cross axis — useful the moment items are different heights and you don't want them all jammed to the top.

Worth remembering: the main axis follows flex-direction, not the other way around. Switch .gear-list to a column, and justify-content starts spacing things out top-to-bottom instead of side-to-side — the two properties don't move, but which direction each one controls flips with the shelf itself.

Common mistake

justify-content and align-items do nothing — silently — without display: flex on their container first. It's an easy line to forget once you're focused on the alignment properties themselves, but they only mean anything on an actual flexbox.

Exercise

Line up a nav bar and a gear list

Two containers below need turning into flexboxes:

- .navdisplay: flex;, justify-content: space-between;, and align-items: center;. - .gear-listdisplay: flex; and flex-direction: column;.