~/
Layout with Flex & Grid
Quiz
...

Layout with Flex & Grid

intermediate · updated Tue Sep 22 2026Contribute

Build page and component layouts with flexbox and grid utilities.

Layout with Flex & Grid

Tailwind exposes flexbox and CSS Grid as utilities. Most layouts come down to a handful of them.

Flexbox

Enable it with flex:

<div class="flex items-center justify-between gap-4">
  <span>Left</span>
  <span>Right</span>
</div>
  • flex — display: flex.
  • items-center — vertical alignment (cross axis).
  • justify-between — horizontal distribution (main axis).
  • gap-4 — space between children.

Flex Direction

<div class="flex flex-col">stacked</div>
<div class="flex flex-row">side by side</div>
<div class="flex flex-wrap">wraps when full</div>

Growing and Shrinking

<div class="flex">
  <aside class="w-64 shrink-0">Sidebar</aside>
  <main class="flex-1">Takes the rest</main>
</div>

flex-1 makes an item fill available space. shrink-0 prevents shrinking.

Centering

The classic: center both axes.

<div class="flex min-h-screen items-center justify-center">
  <div class="rounded-lg bg-white p-8 shadow">Centered</div>
</div>

Grid

Define columns with grid-cols-*:

<div class="grid grid-cols-3 gap-4">
  <div>1</div><div>2</div><div>3</div>
</div>

Responsive columns are common:

<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
  <!-- cards -->
</div>

Column and Row Spans

<div class="grid grid-cols-4 gap-4">
  <div class="col-span-2">Wide</div>
  <div>Normal</div>
  <div>Normal</div>
  <div class="col-span-4">Full width</div>
</div>

Flex or Grid?

  • Flex — one dimension: a row of buttons, a navbar, centering.
  • Grid — two dimensions: card galleries, dashboards, page scaffolding.

They combine well: a grid page with flex components inside each cell.

Best Practices

  1. Use gap — Cleaner than margins between children.
  2. Mobile-first grids — Start at one column, add at breakpoints.
  3. min-w-0 on flex children — Prevents overflow with long content.
  4. Reach for grid for 2D — Do not nest flex three levels deep.

Common Mistakes

  1. Forgetting flex or grid — Alignment classes do nothing without them.
  2. Margin hacks for spacing — Use gap.
  3. Non-responsive grid columnsgrid-cols-4 on mobile overflows.
  4. Overflow from long text — Add min-w-0 or truncate.