Tailwind CSS Tutorial · Layout · Lesson 11 of 27

Flexbox

Building rows and columns with flex: direction, alignment, justification, wrapping, grow and shrink, with live examples.

Create a free account to save this page, take notes and track your progress. Sign in

The essentials

Class Does
flex puts children in a row
flex-col stacks children in a column
items-center centres them on the cross axis (vertically in a row)
justify-between, justify-center, justify-end spreads them on the main axis
gap-4 space between children
flex-wrap wraps onto new lines
flex-1 grow to fill the remaining space
shrink-0 never shrink (icons, avatars)

A navigation bar

A navbar with justify-betweenTry it yourself
<nav class="flex items-center justify-between bg-slate-900 px-6 py-4 text-white">
  <span class="text-lg font-bold">Camel<span class="text-amber-400">.</span></span>
  <div class="flex gap-6 text-sm">
    <a href="#" class="hover:text-amber-400">Docs</a>
    <a href="#" class="hover:text-amber-400">Pricing</a>
    <a href="#" class="hover:text-amber-400">Blog</a>
  </div>
  <button class="rounded-md bg-amber-400 px-3 py-1.5 text-sm font-semibold text-slate-900">Sign in</button>
</nav>

Centring anything

Centring with flexTry it yourself
<div class="flex h-40 items-center justify-center bg-gray-100">
  <div class="rounded-lg bg-white px-6 py-4 shadow">Perfectly centred</div>
</div>

Text overflow in flex rows

A long name pushes buttons off the screen unless the text container may shrink: add min-w-0 to it and truncate to the text.

min-w-0 and truncate in a rowTry it yourself
<div class="max-w-sm space-y-3 p-6">
  <div class="flex items-center gap-3 rounded-lg border p-3">
    <div class="size-10 shrink-0 rounded-full bg-sky-500"></div>
    <div class="min-w-0 flex-1">
      <p class="truncate font-medium">Bartholomew Montgomery-Fitzgerald the Third</p>
      <p class="truncate text-sm text-gray-500">[email protected]</p>
    </div>
    <button class="shrink-0 rounded bg-gray-900 px-3 py-1 text-sm text-white">Follow</button>
  </div>
</div>

Test yourself

Which two classes centre a child horizontally and vertically in a flex container?

  1. items-center and justify-center
  2. text-center and align-middle
  3. mx-auto and my-auto only
  4. center-x and center-y
Show answer

Answer: items-center and justify-center

justify-* aligns along the main axis, items-* along the cross axis.

Was this page helpful?