Lesson 7 / 25

Flexbox

Rows and columns of items.

Direction, alignment and growth

flex makes a flex container; flex-col stacks items vertically. justify-between and justify-center distribute along the main axis, while items-center aligns on the cross axis. flex-1 lets an item grow to fill space, shrink-0 stops shrinking (useful for icons and avatars), and flex-wrap lets items wrap. min-w-0 lets flex children shrink below their content width so truncate can work.

Arrange elements

Flexbox handles one-dimensional layouts, grid handles two-dimensional ones, and positioning layers elements.

Three ideas: flexbox, grid, positioning.
Figure 3.1 — Flexbox, grid and positioning.

A navigation bar

Logo left, links right, vertically centred.

<nav class="flex items-center justify-between gap-6 px-6 py-4 border-b border-gray-200">
  <a href="/" class="text-xl font-bold">Acme</a>
  <ul class="flex items-center gap-4 text-sm font-medium">
    <li><a href="/docs" class="hover:text-cyan-700">Docs</a></li>
    <li><a href="/pricing" class="hover:text-cyan-700">Pricing</a></li>
    <li><a href="/login" class="rounded-md bg-gray-900 px-3 py-1.5 text-white">Log in</a></li>
  </ul>
</nav>

Add min-w-0 when truncation fails

Flex items default to a minimum width of their content, which blocks truncate.

Quick check: Which utility vertically centres items in a horizontal flex row?

  • items-center
  • justify-center
  • text-center
  • content-center-x
Answer

items-center — Cross-axis alignment.