Flexbox Basics

Turn a box into a flex row with the flex utility.

Syntaxclass="flex gap-4"

Add flex to a container and its children line up in a row. Add gap-* for space between them, and use alignment utilities to position them.

  • flex — make a flex row.
  • flex-col — stack in a column.
  • gap-4 — space between items.

The deep-dive chapter covers alignment in detail.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer centers a loading spinner both horizontally and vertically inside a container using flex, items-center, and justify-center.
  • A card footer aligns an icon and a label side by side with consistent spacing using flex and gap-2.
  • A header distributes a logo on the left and navigation links on the right using flex and justify-between.

More examples

Centered flex content

Combining items-center (cross-axis) and justify-center (main axis) centers the child both vertically and horizontally inside the flex parent.

Example · html
<div class="flex items-center justify-center h-48 bg-gray-50">
  <p class="text-gray-600">Perfectly centered</p>
</div>

Flex row with gap

gap-3 adds uniform space between flex children without using margins, making it easy to add or remove buttons without margin adjustments.

Example · html
<div class="flex gap-3">
  <button class="bg-blue-500 text-white px-4 py-2 rounded">Save</button>
  <button class="border border-gray-300 px-4 py-2 rounded">Cancel</button>
</div>

Space-between header

justify-between pushes the logo to the far left and the nav to the far right, with the header's flex layout requiring no additional CSS.

Example · html
<header class="flex items-center justify-between px-6 py-4 bg-white shadow">
  <a href="/" class="text-xl font-bold">Logo</a>
  <nav class="flex gap-4 text-sm text-gray-600">
    <a href="/pricing">Pricing</a>
    <a href="/docs">Docs</a>
  </nav>
</header>

Discussion

  • Be the first to comment on this lesson.
Flexbox Basics — Tailwind CSS | SoundsCode