Flexbox and grid layouts

Tailwind CSS · Essentials · 12 min

Layout utilities let you build navbars, card grids and page shells without leaving the markup.

Tailwind's layout utilities map directly onto CSS flexbox and grid.

Flexbox:

  • flex (or inline-flex), flex-col for a column, flex-wrap.
  • Alignment: items-center, items-start, justify-between, justify-center, self-end.
  • Item sizing: flex-1 (grow and shrink, basis 0), flex-auto, flex-none, grow, shrink-0, basis-64.
  • gap-4 between items, order-first to reorder.

Grid:

  • grid with grid-cols-3 creates three equal columns. The generated CSS is repeat(3, minmax(0, 1fr)), so columns can shrink below their content's width without overflowing.
  • col-span-2 spans two columns; col-span-full spans all; col-start-2 places explicitly.
  • grid-rows-*, row-span-*, grid-flow-col, auto-rows-fr.
  • place-items-center centers content in each cell.

Centering anything takes three classes: flex items-center justify-center, or grid place-items-center.

A common page shell: grid min-h-dvh grid-rows-[auto_1fr_auto] for header, content and footer. A sidebar layout: flex on the wrapper, w-64 shrink-0 on the sidebar and min-w-0 flex-1 on the content, where min-w-0 keeps long content from overflowing.

Layout classes combine with responsive prefixes: grid-cols-1 md:grid-cols-3 is one column on phones and three on wider screens.

Example

<header class="flex items-center justify-between gap-4 px-6 py-3">
  <a href="/" class="font-bold">Acme</a>
  <nav class="flex gap-6 text-sm">
    <a href="/docs">Docs</a><a href="/blog">Blog</a>
  </nav>
  <button class="ml-auto rounded-md bg-gray-900 px-3 py-1.5 text-white">Sign in</button>
</header>

<section class="grid grid-cols-1 gap-6 p-6 md:grid-cols-3">
  <div class="rounded-xl bg-white p-6 shadow md:col-span-2">Featured</div>
  <div class="rounded-xl bg-white p-6 shadow">Side card</div>
  <div class="col-span-full rounded-xl bg-white p-6 shadow">Full width</div>
</section>

<div class="grid h-48 place-items-center bg-gray-100">Perfectly centered</div>

Remember

  • flex + items-center + justify-between covers most toolbars
  • grid-cols-N uses minmax(0, 1fr) columns
  • col-span-* and col-span-full place grid items
  • flex-1 + min-w-0 for content that must shrink

Watch out for

  • Forgetting shrink-0 on a fixed-width sidebar, which then gets squeezed by long content.

Check yourself

  1. What CSS does grid-cols-3 generate?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: tailwindcss.com/docs/grid-template-columns