Sub topic 4
Building layouts with flexbox and grid
This chapter assumes you know how CSS flexbox and grid work in plain CSS: main and cross axes, tracks, and the gap property. It also assumes you have a working Vite and React project with Tailwind v4 installed. Here you will learn which Tailwind utilities correspond to those CSS properties, how to choose between flex and grid, and which mistakes show up most often.
The working model
Tailwind adds no layout system of its own. Each layout utility maps to one CSS declaration, and the browser's layout engine does the rest. The same split applies as in plain CSS: the container (parent) sets the layout mode, and the items (children) tune how they take part in it.
| Utility | CSS it generates |
|---|---|
| `flex` | `display: flex` |
| `grid` | `display: grid` |
| `flex-col` | `flex-direction: column` |
| `items-center` | `align-items: center` |
| `justify-between` | `justify-content: space-between` |
| `gap-4` | `gap: calc(var(--spacing) * 4)` |
| `grid-cols-3` | `grid-template-columns: repeat(3, minmax(0, 1fr))` |
| `col-span-2` | `grid-column: span 2 / span 2` |
The spacing scale is the one from the previous chapter, so gap-4 is the same size as p-4.
Flexbox utilities
Use flexbox for one-dimensional layouts: a row of buttons, a navbar, or a vertical stack. Start with flex on the parent. The default direction is a row. Add flex-col for a column.
Two utility families control alignment:
justify-*aligns along the main axis:justify-start,justify-center,justify-end,justify-between,justify-around,justify-evenly.items-*aligns along the cross axis:items-start,items-center,items-end,items-baseline,items-stretch.
The axes swap when you change direction. In flex-col, justify-* works vertically and items-* works horizontally.
Prefer gap-* over margins between siblings. gap-4 spaces children evenly without adding an outer margin, and it works for both rows and wrapped rows. Use gap-x-* and gap-y-* when the two directions differ.
export function Toolbar({ title }: { title: string }) {
return (
<header className="flex items-center justify-between gap-4 border-b border-gray-200 bg-white px-6 py-3">
<h1 className="truncate text-lg font-semibold text-gray-900">{title}</h1>
<div className="flex shrink-0 items-center gap-2">
<button className="rounded-md px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100">
Share
</button>
<button className="rounded-md bg-blue-600 px-3 py-1.5 text-sm text-white hover:bg-blue-700">
Publish
</button>
</div>
</header>
)
}The title pushes the buttons to the right edge through justify-between. The button group has shrink-0, so a long title can't squash it, and truncate lets the title cut off with an ellipsis instead.
Sizing flex items
Item utilities decide how children share leftover space:
flex-1meansflex: 1 1 0%. The item grows and shrinks from a zero basis, so siblings withflex-1end up with equal widths.growandgrow-0toggleflex-grow.shrink-0stops an item from shrinking below its natural size.basis-1/3orbasis-64sets the starting size before growth or shrinkage.flex-wraplets items drop onto new lines, andflex-nowrapis the default.
A frequent pattern is a fixed-size element beside a flexible one, such as an avatar next to text:
export function Comment({ author, body }: { author: string; body: string }) {
return (
<div className="flex items-start gap-3">
<div className="size-10 shrink-0 rounded-full bg-gray-300" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-gray-900">{author}</p>
<p className="truncate text-sm text-gray-600">{body}</p>
</div>
</div>
)
}The min-w-0 on the text column matters. A flex item has min-width: auto by default, so it refuses to shrink below the width of its content. Without min-w-0, truncate has no effect, because the column never gets narrower than the long text.
Grid utilities
Use grid for two-dimensional layouts, where rows and columns must line up. grid-cols-N defines N equal columns, and grid-rows-N does the same for rows. Items then flow into cells automatically.
Children can span tracks with col-span-* and row-span-*. Use col-start-* and col-end-* to place an item on specific lines. col-span-full stretches an item across every column.
export function Dashboard() {
return (
<div className="grid grid-cols-4 gap-4 p-6">
<section className="col-span-4 rounded-lg bg-white p-4 shadow-sm">
Summary
</section>
<section className="col-span-3 rounded-lg bg-white p-4 shadow-sm">
Activity
</section>
<aside className="col-span-1 rounded-lg bg-white p-4 shadow-sm">
Notes
</aside>
</div>
)
}Columns that adapt without breakpoints
Fixed column counts need breakpoint variants to adapt to screen size, which the next chapter covers. A different approach lets the browser decide the count. Tailwind accepts a square-bracket value for grid-template-columns, and underscores stand for spaces:
export function AutoGrid({ children }: { children: React.ReactNode }) {
return (
<div className="grid grid-cols-[repeat(auto-fill,minmax(16rem,1fr))] gap-4">
{children}
</div>
)
}This creates as many columns of at least 16rem as fit, and the columns share the leftover width. It is a legitimate use of an arbitrary value, because no named utility expresses it.
Fixed sidebar plus flexible content
A named column and a flexible column is a common layout. Grid expresses it more directly than flex:
export function AppShell({ children }: { children: React.ReactNode }) {
return (
<div className="grid min-h-screen grid-cols-[14rem_1fr] grid-rows-[auto_1fr]">
<header className="col-span-2 border-b border-gray-200 bg-white px-6 py-3">
My app
</header>
<nav className="border-r border-gray-200 bg-gray-50 p-4">Navigation</nav>
<main className="min-w-0 p-6">{children}</main>
</div>
)
}The header spans both columns. The second row takes the remaining height because of 1fr, and min-h-screen makes the shell at least as tall as the viewport.
Choosing between flex and grid
| Situation | Better fit | Reason |
|---|---|---|
| Items in one row or column, sized by content | Flex | Content decides the size, and alignment is simple |
| Rows and columns must line up across items | Grid | Tracks are shared by all children |
| Items wrap and should keep a consistent width | Grid | Wrapped flex rows don't align to each other |
| Centering one child inside a box | Either | `flex items-center justify-center` or `grid place-items-center` |
| Layout defined by the container, not the content | Grid | Track sizes come from the parent |
You can nest them freely. A grid of cards, each card a flex flex-col, is a normal structure.
Common errors
- Alignment utilities with no
flexorgrid.items-centerandjustify-betweendo nothing on adisplay: blockelement. Check that the parent hasflexorgrid. - Mixing up the axes. If
justify-centerseems to center horizontally in aflex-colcontainer, look again: it centers vertically there. Useitems-centerfor horizontal centering. - Text that won't truncate or wrap. Add
min-w-0to the flex or grid child that holds the long text. Grid items have the samemin-width: autobehavior as flex items. - Spacing with
space-x-*in wrapped layouts. Thespace-*utilities add margins between siblings and misbehave when items wrap. Usegap-*. - Stretched items you didn't want. The default is
items-stretch, so children in a row grow to the tallest sibling. Additems-startif you want natural heights. - Building column classes from variables.
col-span-${n}is not detected, because Tailwind only finds complete class names in source text. Map each value to a full string:
const spans = {
1: 'col-span-1',
2: 'col-span-2',
3: 'col-span-3',
} as const
export function Cell({ span, children }: { span: keyof typeof spans; children: React.ReactNode }) {
return <div className={spans[span]}>{children}</div>
}Exercise
A flex row holds an icon, a long file name, and a "Delete" button. The file name pushes the button off the edge of the screen instead of showing an ellipsis. Which utilities fix this, and on which elements?
Show answer
Put min-w-0 and flex-1 on the file name element, and add truncate to it so the text is cut off with an ellipsis. Put shrink-0 on the icon and on the button so they keep their size. min-w-0 is needed because a flex item won't shrink below its content width by default.
Exercise
You need a page with a header across the top, a 12rem sidebar on the left, and a main area that fills the rest. Would you choose flex or grid, and what are the container classes?
Show answer
Grid fits best because the layout has fixed and flexible tracks in two directions. A container such as grid min-h-screen grid-cols-[12rem_1fr] grid-rows-[auto_1fr] works, with the header using col-span-2.