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
- Use
gap— Cleaner than margins between children. - Mobile-first grids — Start at one column, add at breakpoints.
min-w-0on flex children — Prevents overflow with long content.- Reach for grid for 2D — Do not nest flex three levels deep.
Common Mistakes
- Forgetting
flexorgrid— Alignment classes do nothing without them. - Margin hacks for spacing — Use
gap. - Non-responsive grid columns —
grid-cols-4on mobile overflows. - Overflow from long text — Add
min-w-0ortruncate.