Flexbox and Grid

Build a Grid layout

Create explicit and responsive Grid tracks with Tailwind utilities, fractional columns, gaps, spans, and arbitrary track definitions.

Three equal columns in Tailwind take one line:

<div class="grid grid-cols-3 gap-6">...</div>

Grid is a two-dimensional layout model. The parent defines rows and columns, called tracks, and direct children are placed into the cells.

grid-cols-3 generates grid-template-columns: repeat(3, minmax(0, 1fr)). Each column gets an equal share of the width, and the minmax(0, ...) part lets columns shrink below their content size instead of overflowing.

Three columns are not responsive

On a phone, three columns are three narrow strips. Start with one column, and add tracks when there’s room:

<div class="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">...</div>

The base is a single column. At sm you get two, at lg three. This is the mobile-first pattern we’ll use throughout the course.

Spanning tracks

An item can span more than one track when the content deserves it:

<article class="sm:col-span-2">Featured story</article>

Use spans for hierarchy, like a featured article that’s twice as wide. Don’t use them to rebuild pixel coordinates from a design file. Keep the source order meaningful, because keyboard and screen-reader users follow the DOM, not the visual grid. If the visual placement turns the DOM into a puzzle, the layout is wrong.

Let the content decide the columns

Instead of guessing viewport breakpoints, you can tell Grid how wide each card should be and let it figure out the count:

<div class="grid grid-cols-[repeat(auto-fit,minmax(16rem,1fr))] gap-6">
  ...
</div>

Each card needs at least 16rem. auto-fit creates as many columns as fit in the container, and 1fr shares the leftover space between them. Resize the window and the columns appear and disappear on their own, with no breakpoint variants. Test the 16rem minimum with real content, including translated text and 200% zoom.

Flexbox or Grid?

Use Flexbox when one axis drives the layout, like a toolbar or a row of tags. Use Grid when rows and columns need to line up, or when the container should define the tracks. You can nest one inside the other, and I do that all the time: a Grid of cards where each card is a vertical Flexbox.

Try this: build the same card list twice, once with sm:grid-cols-2 lg:grid-cols-3 and once with auto-fit. Resize the container, open the Grid overlay in DevTools, and decide which behavior matches what the content needs.

Lesson completed