The Complete Tailwind CSS 4 Guide and Cheat Sheet

By

Published · Updated

Tagged: CSS

Learn Tailwind CSS 4 from setup to production: spacing, typography, OKLCH colors, Flexbox, Grid, container queries, dark mode, @theme, and a full project.

If you know basic HTML and CSS and want to build clean, responsive interfaces without wrestling with giant stylesheets or inventing class names all afternoon, this guide is for you.

I was skeptical of Tailwind CSS when I first saw it. Putting a string of tiny classes directly inside HTML looked messy compared to the neat semantic CSS classes I had written for years.

Then I tried it on a real project. Within two days I stopped switching back and forth between HTML and CSS files, stopped worrying about whether deleting a rule would break another page, and shipped cleaner layouts in half the time.

In this guide we learn Tailwind CSS v4 from scratch. We start with what Tailwind is and how to install it, walk through Preflight, spacing, typography, colors, borders, Flexbox, CSS Grid, responsive design, container queries, interactive states, dark mode, @theme customization, custom utilities, forms, animations, a complete end-to-end landing page project, common pitfalls, and a full CSS-to-Tailwind reference at the end.

Every CLI command, timing, and output size in this guide was tested live on my Mac:

SoftwareVersion
Tailwind CSS (tailwindcss)4.3.5
CLI & Vite plugins@tailwindcss/cli 4.3.5, @tailwindcss/vite 4.3.5
Node.js22.23.5

What is Tailwind CSS (and what changed in v4)?

When we style a web app with traditional CSS, we invent class names for every component and every tiny wrapper: .card, .card-header, .card-header-inner, .card-title-lg.

Over a few months, that stylesheet grows into an append-only file. Nobody feels safe deleting old rules because it is hard to prove which template still depends on .sidebar-box-alt.

Tailwind takes the opposite path. Instead of writing custom classes that bundle ten CSS properties together, we compose small utility classes right in our HTML where each class does one single job:

  • p-6 sets padding: 1.5rem
  • rounded-xl sets border-radius: 0.75rem
  • bg-white sets background-color: #ffffff
  • shadow-sm adds a soft drop shadow

Let’s compare a small card written in traditional CSS versus Tailwind.

With plain CSS, we split the markup and styling across two files:

<!-- index.html -->
<article class="book-card">
  <h2 class="book-card-title">Tailwind CSS Handbook</h2>
  <p class="book-card-summary">Build responsive interfaces fast.</p>
</article>
/* styles.css */
.book-card {
  max-width: 24rem;
  padding: 1.5rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.75rem;
  background-color: #ffffff;
}

.book-card-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #0f172a;
}

.book-card-summary {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: #475569;
}

With Tailwind, everything lives in one spot:

<article class="max-w-sm rounded-xl border border-slate-200 bg-white p-6">
  <h2 class="text-lg font-semibold text-slate-900">Tailwind CSS Handbook</h2>
  <p class="mt-2 text-sm text-slate-600">Build responsive interfaces fast.</p>
</article>

When you delete that card next month, its styles disappear automatically. Nothing lingers in a forgotten stylesheet.

How Tailwind CSS v4 builds your stylesheet

A common beginner worry is: “Does Tailwind ship thousands of unused CSS classes to my users?”

No. Tailwind v4 includes a Rust-powered engine called Oxide that scans your HTML, Astro, JSX, Vue, Svelte, or PHP files at build time and emits only the utility classes it actually saw in your code.

Your HTML / Astro /JSXtemplatesTailwind v4 Oxideengine(scans used classnames)src/app.css@import'tailwindcss' +@themedist/app.css(only the classesyou used)

A typical production site ends up with a tiny 5 KB to 15 KB gzipped stylesheet, no matter how many pages you add.

What changed in Tailwind CSS v4

If you read tutorials written before 2025, you will see tailwind.config.js files and @tailwind base; directives everywhere. Tailwind v4 simplified almost all of that:

AreaTailwind v3Tailwind v4
CSS entry@tailwind base; @tailwind components; @tailwind utilities;Single @import "tailwindcss";
ConfigurationJavaScript tailwind.config.jsNative CSS @theme { ... } right in your stylesheet
Template scanningManual content: ['./src/**/*.{html,js}'] glob arrayAutomatic project scanning (respects .gitignore)
Spacing scaleFixed list of predefined numbersDynamic --spacing scale (any multiplier like p-13 works)
Color spaceRGB / hex paletteWide-gamut OKLCH palette exposed as CSS custom properties
Container queriesRequired @tailwindcss/container-queries pluginBuilt straight into core (@container, @md:)
Gradientsbg-gradient-to-rbg-linear-to-r, bg-radial, bg-conic
Important modifierLeading ! (!text-red-600)Trailing ! (text-red-600!)

Every example in this handbook uses clean, modern Tailwind CSS v4 syntax.

Installing Tailwind CSS v4

Let’s wire Tailwind into a real project right away. Pick the setup that matches your stack.

Option 1: Vite, Astro, React, or Svelte (@tailwindcss/vite)

If your project uses Vite (including Astro, React with Vite, Vue, or SvelteKit), install Tailwind and its official Vite plugin:

npm install -D tailwindcss @tailwindcss/vite

Add the plugin to vite.config.ts (or astro.config.mjs under vite.plugins):

import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
  plugins: [tailwindcss()],
})

Create src/app.css with a single line:

@import "tailwindcss";

Import ./app.css in your main JavaScript entry file or layout template, start npm run dev, and every Tailwind utility works immediately with instant hot reload.

Option 2: Standalone CLI (@tailwindcss/cli)

If you are styling plain HTML files, Laravel Blade, Rails, Django, Go templates, or PHP without a JavaScript bundler, the standalone CLI is all you need.

Create a project folder and install the CLI:

mkdir tailwind-demo
cd tailwind-demo
npm init -y
npm install -D tailwindcss @tailwindcss/cli

Create src/app.css:

@import "tailwindcss";

@theme {
  --color-brand: #2563eb;
  --color-paper: #faf9f6;
  --font-display: "Instrument Serif", Georgia, serif;
}

Create index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Tailwind v4 Demo</title>
    <link rel="stylesheet" href="./dist/app.css" />
  </head>
  <body class="bg-paper text-slate-900 antialiased">
    <main class="mx-auto max-w-2xl px-6 py-16">
      <h1 class="font-display text-4xl font-bold tracking-tight">Tailwind v4</h1>
      <button class="mt-6 rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:opacity-90">
        Get started
      </button>
    </main>
  </body>
</html>

During development, run Tailwind with --watch so it recompiles every time you save a file:

npx @tailwindcss/cli -i src/app.css -o dist/app.css --watch

For production, swap --watch for --minify:

npx @tailwindcss/cli -i src/app.css -o dist/app.css --minify

Here is a real Tailwind CSS 4.3.5 build of that exact project on my Mac, finishing in 24 ms and outputting 5.9 KB minified (2.0 KB gzipped):

Compiling a Tailwind CSS 4.3.5 stylesheet with @theme tokens in 24 ms

Option 3: Next.js and PostCSS (@tailwindcss/postcss)

Frameworks built on PostCSS (such as Next.js) use @tailwindcss/postcss:

npm install -D tailwindcss @tailwindcss/postcss postcss

Add the plugin in postcss.config.mjs:

export default {
  plugins: {
    '@tailwindcss/postcss': {},
  },
}

Then put @import "tailwindcss"; at the top of app/globals.css.

Editor setup: Tailwind CSS IntelliSense

Before we go further, install the official Tailwind CSS IntelliSense extension in VS Code or Cursor.

It gives you autocomplete for every class name (including your custom @theme tokens), shows color swatches beside color classes, and reveals the exact CSS output when you hover over any class.

If VS Code shows a yellow warning saying Unknown at rule @theme or Unknown at rule @utility inside your CSS file, associate .css files with Tailwind CSS (or set "css.lint.unknownAtRules": "ignore" in your editor settings). I wrote a quick fix guide on fixing unknown at-rule warnings for Tailwind if you run into it.

Preflight and how Tailwind thinks about CSS

The first time you add @import "tailwindcss"; to an existing HTML page, you might notice something surprising: your <h1> shrinks to normal body size, bullet points disappear from <ul>, and default margins vanish.

That comes from Preflight, Tailwind’s built-in modern CSS reset.

What Preflight resets for you

Preflight smooths out browser inconsistencies so Chrome, Safari, and Firefox start from the same clean baseline:

  • Sets box-sizing: border-box everywhere so padding and border never blow up your widths.
  • Removes default margins from headings, paragraphs, figure, and blockquote.
  • Strips default font sizes and bold weights from h1 through h6 so you pick headings for HTML semantics, not visual size.
  • Removes default bullets and left padding from ul and ol (since half the lists on modern sites are navbars and menus).
  • Makes img, svg, and video display: block and max-width: 100% so images never leave a weird 4px gap underneath or overflow narrow phone screens.

CSS Cascade Layers in Tailwind v4

Tailwind v4 organizes its generated CSS using native CSS @layer rules in a strict priority order:

1. @layer theme(CSS variables from@theme)2. @layer base(Preflight + elementdefaults)3. @layer components(Optional customcomponents)4. @layer utilities(All utility classeswin)

Because utilities is the last layer, a utility class like p-8 always overrides a base style in @layer base or a component class in @layer components without fighting specificity wars.

One warning: any raw CSS rule you write outside a @layer (unlayered CSS) beats every layered rule in the CSS spec! Always wrap custom global styles inside @layer base { ... } so Tailwind utilities can still override them.

Stacking variants and the ! important modifier

You can chain as many prefixes (called variants) as you want before any utility class, separated by colons:

<button class="bg-blue-600 text-white hover:bg-blue-700 md:px-6 dark:bg-blue-500 dark:hover:bg-blue-400">
  Subscribe
</button>

When you genuinely need !important (for example, overriding a third-party widget’s inline stylesheet), put ! at the end of the class name in Tailwind v4:

<div class="bg-white! text-slate-900!">Forced override</div>

Spacing, sizing, and layout primitives

We use spacing and sizing classes on almost every element, so learning how the scale works pays off immediately.

How the dynamic --spacing scale works

In Tailwind v4, every spacing utility (p-*, m-*, gap-*, w-*, h-*, inset-*) multiplies a single CSS variable: --spacing, which defaults to 0.25rem (4px at the standard 16px browser root font size).

That makes mental math effortless: multiply the Tailwind number by 4 to get pixels:

UtilityCalculationResult
p-0.50.5 * 4px2px (0.125rem)
p-11 * 4px4px (0.25rem)
p-22 * 4px8px (0.5rem)
p-33 * 4px12px (0.75rem)
p-44 * 4px16px (1rem)
p-66 * 4px24px (1.5rem)
p-88 * 4px32px (2rem)
p-1212 * 4px48px (3rem)

Because Tailwind v4 computes calc(var(--spacing) * N) dynamically, any number works out of the box. Need mt-13 (52px) or w-75 (300px)? Just write it.

Padding, margin, and logical directions

Control individual sides with directional letters:

  • p-4 / m-4: all four sides
  • px-4 / mx-4: left and right
  • py-2 / my-6: top and bottom
  • pt-6, pr-4, pb-6, pl-4: top, right, bottom, left
  • ps-4, pe-4, ms-auto, me-2: logical inline-start and inline-end (these flip cleanly if your site ever supports right-to-left languages like Arabic or Hebrew)
  • mx-auto: centers a block that has a max-w-* or fixed width
  • -mt-6: negative margin (prefix with a dash -)

gap-* vs space-y-*

When you want consistent breathing room between sibling elements, I reach for gap-* inside a flex or grid container 95% of the time:

<div class="flex flex-col gap-4">
  <p>First paragraph</p>
  <p>Second paragraph</p>
  <p>Third paragraph</p>
</div>

space-y-4 adds top margin to every child except the first, which works on plain block containers, while gap-4 handles wrapped rows cleanly and never leaves stray margins when elements hide or reorder.

Width, height, size-*, and viewport units

  • Container widths: max-w-sm (24rem), max-w-md (28rem), max-w-lg (32rem), max-w-2xl (42rem), max-w-5xl (64rem), max-w-7xl (80rem), and max-w-prose (65ch, ideal line length for comfortable reading!).
  • Fractions and full width: w-full (100%), w-1/2, w-1/3, w-2/3, w-fit, w-auto.
  • Equal width and height: Use size-10 instead of typing w-10 h-10 on avatars, icons, and square buttons.
  • Full-height pages on mobile: Prefer min-h-dvh (100dvh, dynamic viewport height) over min-h-screen (100vh). On iOS Safari, 100vh includes the area hidden behind the address bar, which pushes footers off-screen. min-h-dvh adjusts cleanly as the mobile bar expands and collapses.

Display, overflow, and aspect ratios

Control image framing and overflow cleanly:

<div class="aspect-video w-full overflow-hidden rounded-xl bg-slate-100">
  <img
    src="/images/desk.jpg"
    alt="Workspace"
    class="size-full object-cover"
  />
</div>

aspect-video locks a 16 / 9 box (use aspect-square for 1 / 1 or aspect-4/3 for 4 / 3), and size-full object-cover crops the photo cleanly without stretching it.

Typography

Clean typography makes even a simple layout look like a designer touched it. Tailwind covers font families, sizes, weights, line heights, letter spacing, and modern wrapping rules.

Font scale, weight, and line height

<header class="max-w-2xl space-y-3">
  <p class="text-xs font-semibold tracking-wider text-blue-600 uppercase">
    Handbook
  </p>
  <h1 class="text-4xl/tight font-bold tracking-tight text-balance text-slate-900">
    Style modern web apps faster with Tailwind CSS v4
  </h1>
  <p class="text-lg/relaxed text-pretty text-slate-600">
    Once you learn twenty core utilities, you can build almost any layout without leaving your HTML template.
  </p>
</header>

Notice three tiny utilities in that header that elevate readability immediately:

  • text-4xl/tight and text-lg/relaxed: the slash shorthand sets both font-size and line-height in one token (you can also pass spacing numbers like text-base/7).
  • text-balance: asks the browser to balance line lengths on multi-line headings so you never get one awkward lonely word on the second line.
  • text-pretty: avoids single-word orphans at the end of body paragraphs.

Truncation, line clamping, and tabular-nums

  • truncate clips single-line text with an ellipsis (...) when space runs out.
  • line-clamp-2 or line-clamp-3 limits multi-line card excerpts to two or three lines with a clean ellipsis.
  • tabular-nums gives every digit (0 through 9) the same width. Always put tabular-nums on prices, countdown timers, dashboard metrics, and table columns so numbers align straight down vertically:
<div class="flex items-baseline justify-between border-b border-slate-200 py-2 text-sm">
  <span class="text-slate-600">Monthly revenue</span>
  <span class="font-mono font-semibold text-slate-900 tabular-nums">$12,480.00</span>
</div>

Because Preflight strips bullets from lists, opt back in whenever you want a real bulleted or numbered list inside your UI:

<ul class="list-disc space-y-1.5 pl-5 text-slate-700 marker:text-blue-600">
  <li>Zero JavaScript config required</li>
  <li>Compiles production CSS in milliseconds</li>
  <li>Built-in container queries and OKLCH colors</li>
</ul>

For inline links, underline decoration-slate-300 underline-offset-4 hover:decoration-blue-600 looks much sharper than the default browser underline glued straight to the letters.

Colors, backgrounds, and gradients

Tailwind v4 ships an updated color palette defined in OKLCH, a modern perceptual color space that keeps brightness consistent across hues and unlocks richer colors on modern displays.

Reading the 50 to 950 shade ladder

Every color family runs across 11 shades (50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950). Once you learn what each range is for, picking harmonious colors takes seconds:

Shade rangeBest used forExample
50 to 100Soft page tints, badge backgrounds, subtle hover fillsbg-blue-50, hover:bg-slate-100
200 to 300Borders, dividers, muted input outlinesborder-slate-200, divide-slate-200
400 to 500Placeholder text, subtle icons, primary accentstext-slate-400, bg-blue-500
600 to 700Primary buttons, links, strong badges (high contrast with white text!)bg-blue-600 text-white, text-emerald-700
800 to 950Headings, body text, dark-mode surfacestext-slate-900, dark:bg-slate-950

Pick ONE neutral gray family per project

Tailwind includes five neutral gray families with slightly different undertones:

  • slate: cool blue-gray (my favorite default for developer tools and SaaS apps)
  • gray: slightly softer cool gray
  • zinc: crisp neutral-cool gray (great for minimal monochrome UIs)
  • neutral: pure zero-tint gray
  • stone: warm paper-like gray (great for blogs, editorial sites, and reading apps)

Pick one neutral family at the start of a project and stick to it everywhere. Mixing slate-200 borders with stone-500 text makes a page feel subtly off without being obvious why.

Opacity modifiers and arbitrary colors

Append /opacity to any color utility (bg-, text-, border-, ring-, shadow-) to adjust transparency cleanly:

<span class="inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 px-3 py-1 text-xs font-medium text-emerald-700 ring-1 ring-emerald-600/20">
  <span class="size-1.5 rounded-full bg-emerald-500"></span>
  Live
</span>

When you need a one-off hex or OKLCH value without adding it to @theme, wrap it in square brackets: bg-[#faf9f6] or text-[oklch(0.45_0.2_260)].

Gradients in Tailwind v4

Tailwind v4 modernized gradient utilities to match standard CSS gradient names:

  • Linear gradients: bg-linear-to-r, bg-linear-to-b, bg-linear-to-br, or exact angles like bg-linear-45.
  • Radial and conic gradients: bg-radial and bg-conic.
  • Color stops: from-*, optional via-*, and to-*.
<div class="rounded-2xl bg-linear-to-br from-blue-600 via-indigo-600 to-violet-600 p-8 text-white">
  <h2 class="text-2xl font-bold">Ship faster with Tailwind v4</h2>
  <p class="mt-2 text-blue-100">Modern linear, radial, and conic gradients built right in.</p>
</div>

You can also create gradient headline text in one line with bg-linear-to-r from-blue-600 to-violet-600 bg-clip-text text-transparent.

Borders, shadows, rings, and positioning

Once your spacing, type, and colors feel right, borders, elevation, and positioning give your interface clear structure.

Borders, corners, and dividers

In Tailwind v4, the default border color changed from gray (gray-200 in v3) to currentColor so it matches standard CSS. Always pass an explicit border color like border-slate-200:

<div class="rounded-2xl border border-slate-200 bg-white shadow-xs">
  <div class="border-b border-slate-200 px-6 py-4">
    <h3 class="font-semibold text-slate-900">Recent deploys</h3>
  </div>
  <ul class="divide-y divide-slate-200">
    <li class="px-6 py-3 text-sm text-slate-700">Production (2 minutes ago)</li>
    <li class="px-6 py-3 text-sm text-slate-700">Staging (18 minutes ago)</li>
  </ul>
</div>

Notice divide-y divide-slate-200 on the <ul>. It draws crisp 1px lines between child items without putting an extra stray line above the first item or below the last item!

For corner radii, rounded-md, rounded-lg, rounded-xl, rounded-2xl, and rounded-full cover 99% of UI elements.

Shadows, rings, and frosted glass

Tailwind v4 refined its shadow scale to start softer (shadow-2xs, shadow-xs, shadow-sm, shadow-md, shadow-lg, shadow-xl), and added inset-shadow-xs and inset-ring for subtle tactile buttons.

For frosted-glass sticky headers, pair semi-transparent backgrounds with backdrop-blur-md:

<header class="sticky top-0 z-20 border-b border-slate-200/80 bg-white/80 backdrop-blur-md">
  <div class="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">
    <a href="/" class="font-bold text-slate-900">BookShelf</a>
    <a href="/pricing" class="text-sm font-medium text-slate-600 hover:text-slate-900">Pricing</a>
  </div>
</header>

Positioning (relative, absolute, fixed, sticky)

  • relative on a parent creates the positioning anchor for an absolute child inside it (for example, placing an unread dot in the top-right corner of an avatar):
<div class="relative inline-block">
  <img src="/avatar.jpg" alt="Flavio" class="size-10 rounded-full object-cover" />
  <span class="absolute -top-0.5 -right-0.5 size-3 rounded-full bg-emerald-500 ring-2 ring-white"></span>
</div>
  • fixed inset-0 z-50 covers the whole viewport (for modal backdrops and drawers).
  • sticky top-0 z-20 scrolls normally until it reaches the top of the viewport, then pins itself there.

Flexbox layout in depth

Flexbox lays out items along a single axis: either a horizontal row (flex) or a vertical column (flex-col).

The alignment table that stops confusion forever

Almost every beginner mixes up items-* and justify-* at first. Remember one rule: justify-* moves along the main axis, and items-* moves along the cross axis.

ClassIn a horizontal row (flex)In a vertical column (flex-col)
justify-startPush leftPush top
justify-centerCenter horizontallyCenter vertically
justify-betweenFirst left, last right, even gapsFirst top, last bottom
justify-endPush rightPush bottom
items-startAlign to top edgeAlign to left edge
items-centerVertically center itemsHorizontally center items
items-stretchEqual heights (default)Full width (default)
items-baselineAlign text baselinesAlign text baselines

Controlling how children grow and shrink

  • flex-1 lets a child expand to eat all remaining empty space (awesome for main content between a header and footer, or a search input beside a button).
  • shrink-0 prevents an icon, avatar, or badge from getting squished when a long title next to it runs out of room.
  • min-w-0 on a flex child enables truncate to work inside a flex row (a famous CSS gotcha!).

Four everyday Flexbox patterns

  1. Sticky footer page shell (footer always sits at the bottom even on short pages):
<body class="flex min-h-dvh flex-col bg-white text-slate-900">
  <header class="border-b border-slate-200 px-6 py-4">Header</header>
  <main class="mx-auto w-full max-w-4xl flex-1 px-6 py-12">Main content</main>
  <footer class="border-t border-slate-200 px-6 py-6 text-sm text-slate-500">Footer</footer>
</body>
  1. Row with avatar, truncating title, and fixed badge:
<div class="flex items-center gap-3 rounded-xl border border-slate-200 p-4">
  <div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-blue-600 font-bold text-white">
    TS
  </div>
  <div class="min-w-0 flex-1">
    <p class="truncate font-semibold text-slate-900">TypeScript Handbook</p>
    <p class="truncate text-sm text-slate-500">Practical types, narrowing, and Zod validation</p>
  </div>
  <span class="shrink-0 rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-700">
    43 pages
  </span>
</div>
  1. Icon + label button: inline-flex items-center gap-2 rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white.
  2. Wrapping tag cloud: flex flex-wrap items-center gap-2.

CSS Grid layout in depth

Whenever you want a two-dimensional layout (rows and columns), equal-width cards, or a sidebar next to fluid content, CSS Grid is cleaner than nesting three flex containers.

Responsive card grids and spanning

<section class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
  <article class="rounded-xl border border-slate-200 p-6">Card 1</article>
  <article class="rounded-xl border border-slate-200 p-6">Card 2</article>
  <article class="rounded-xl border border-slate-200 p-6 sm:col-span-2 lg:col-span-1">
    Card 3
  </article>
</section>

Want a sidebar of exactly 260px next to a fluid main panel on desktop? Use an arbitrary grid template:

<div class="grid grid-cols-1 gap-8 lg:grid-cols-[260px_1fr]">
  <aside class="rounded-xl border border-slate-200 p-4">Sidebar navigation</aside>
  <main class="min-w-0">Article content</main>
</div>

Want cards that wrap automatically to fit any width without writing breakpoint classes at all? Combine CSS repeat(auto-fit, minmax(...)):

<div class="grid grid-cols-[repeat(auto-fit,minmax(240px,1fr))] gap-6">
  <!-- Any number of cards -->
</div>

Aligning nested card footers with subgrid

Ever built a 3-column grid where one card has a longer title and pushes its footer button out of alignment with its neighbors?

CSS subgrid solves that cleanly by letting each card inherit the parent grid’s row tracks (grid-rows-subgrid row-span-3):

<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
  <article class="row-span-3 grid grid-rows-subgrid gap-3 rounded-xl border border-slate-200 p-6">
    <h3 class="text-lg font-semibold">Short title</h3>
    <p class="text-sm text-slate-600">One short line.</p>
    <a href="#" class="self-end text-sm font-medium text-blue-600">Read more -></a>
  </article>
  <article class="row-span-3 grid grid-rows-subgrid gap-3 rounded-xl border border-slate-200 p-6">
    <h3 class="text-lg font-semibold">A much longer multi-line card title</h3>
    <p class="text-sm text-slate-600">Two or three sentences explaining the feature in full detail.</p>
    <a href="#" class="self-end text-sm font-medium text-blue-600">Read more -></a>
  </article>
</div>

When to pick Flexbox vs CSS Grid

Layout needBest choiceStarting classes
Navbar, toolbar, button with icon, tag pillsFlexboxflex items-center justify-between gap-4
Center one box horizontally and verticallyGrid (shortest!)grid place-items-center min-h-dvh
Multi-column cards or pricing tiersGridgrid grid-cols-1 md:grid-cols-3 gap-6
Fixed sidebar + fluid main areaGridgrid grid-cols-1 lg:grid-cols-[260px_1fr] gap-8
Bento dashboard with mixed card spansGridgrid grid-cols-1 md:grid-cols-4 gap-4 + md:col-span-2

Responsive design and container queries

Tailwind is mobile-first. Every unprefixed class applies at 0px and up (phones first), and breakpoint prefixes layer overrides as the viewport grows wider.

No prefix(0px+ / Phones)grid-cols-1 p-4sm: >= 640pxsm:grid-cols-2md: >= 768pxmd:p-8lg: >= 1024pxlg:grid-cols-3xl: >= 1280pxxl:grid-cols-4
PrefixMinimum widthCSS media query
(none)0pxDefault (all screens)
sm:40rem (640px)@media (width >= 40rem)
md:48rem (768px)@media (width >= 48rem)
lg:64rem (1024px)@media (width >= 64rem)
xl:80rem (1280px)@media (width >= 80rem)
2xl:96rem (1536px)@media (width >= 96rem)

Here is the mistake almost everyone makes on day one: writing sm:text-center thinking sm: means “only on small screens”. It means 640px and wider!

To center text on phones and left-align it from tablets up, write text-center md:text-left.

If you genuinely need a style to apply only below a breakpoint (like hiding a desktop sidebar below md), Tailwind v4 supports max-* variants too: max-md:hidden or range variants like md:max-lg:grid-cols-2.

Built-in container queries (@container)

Viewport breakpoints break down when the same reusable card sits inside a wide hero section on one page and a narrow 300px sidebar on another.

Tailwind v4 builds CSS container queries right into core with zero plugins. Put @container on the parent wrapper, then style children based on the parent’s width with @sm: (24rem), @md: (28rem), @lg: (32rem), and @xl: (36rem):

<div class="@container">
  <article class="flex flex-col gap-4 rounded-xl border border-slate-200 bg-white p-4 @md:flex-row @md:items-center">
    <img
      src="/images/cover.jpg"
      alt="Handbook cover"
      class="h-36 w-full rounded-lg object-cover @md:size-28 @md:shrink-0"
    />
    <div class="space-y-1">
      <h3 class="font-semibold text-slate-900">Tailwind CSS Handbook</h3>
      <p class="text-sm text-slate-600">
        Stacks vertically in a narrow sidebar and switches to a horizontal row in a wide column.
      </p>
    </div>
  </article>
</div>

If you nest containers inside each other, name them (@container/sidebar and @md/sidebar:flex-row) so inner components listen to the exact ancestor they care about.

Interactive states, dark mode, and accessibility

Prefix any utility with state variants to handle hover, focus, sibling inputs, parent hovers, data attributes, and dark mode without writing a single CSS selector by hand.

Hover, focus, active, and disabled

<button
  class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 active:scale-98 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:cursor-not-allowed disabled:opacity-50"
>
  Save changes
</button>

I always use focus-visible: instead of focus: on buttons and links. That keeps keyboard Tab navigation crystal clear while stopping mouse clicks from leaving a lingering blue box behind.

Relational states: group, peer, and has-

  1. Style a child when its parent is hovered (group + group-hover:):
<a
  href="/ebooks/tailwind-css-handbook/"
  class="group flex items-center justify-between rounded-xl border border-slate-200 p-4 hover:border-blue-500"
>
  <span class="font-medium text-slate-900 group-hover:text-blue-600">Read the handbook</span>
  <span class="text-slate-400 transition-transform group-hover:translate-x-1 group-hover:text-blue-600">
    ->
  </span>
</a>
  1. Style a sibling based on an input (peer + peer-checked:):
<label class="flex cursor-pointer items-center gap-3">
  <input type="checkbox" class="peer sr-only" />
  <span class="flex size-5 items-center justify-center rounded border border-slate-300 peer-checked:border-blue-600 peer-checked:bg-blue-600 peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-blue-600"></span>
  <span class="text-sm text-slate-700 peer-checked:font-medium peer-checked:text-slate-900">
    Remember me
  </span>
</label>
  1. Style a parent based on what is inside it (has-[...]):

Modern CSS :has() is supported directly in Tailwind v4 and makes radio cards ridiculously clean:

<label class="flex cursor-pointer items-start gap-3 rounded-xl border border-slate-200 p-4 has-checked:border-blue-600 has-checked:bg-blue-50/50">
  <input type="radio" name="plan" value="pro" class="mt-1 accent-blue-600" />
  <div>
    <p class="font-semibold text-slate-900">Pro Plan</p>
    <p class="text-sm text-slate-600">Unlimited projects and priority support.</p>
  </div>
</label>

You can also style all direct children at once with *: (for example, *:px-3 on a button group) or match ARIA/data attributes directly (aria-expanded:rotate-180, data-[open]:block).

Dark mode (OS preference vs manual toggle)

Out of the box, the dark: variant follows the user’s operating system setting (prefers-color-scheme: dark):

<div class="border border-slate-200 bg-white text-slate-900 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-100">
  Works in both light and dark themes automatically
</div>

If your site includes a light/dark theme toggle button that puts a .dark class on <html>, add one line right below @import "tailwindcss"; in src/app.css:

@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));

That tells Tailwind v4 to activate dark: utilities whenever .dark is present on <html> (or any ancestor). Pair it with color-scheme: light dark; so browser scrollbars and native date pickers match your active theme too.

Accessibility utilities you should use every week

  • sr-only: hides text visually while keeping it readable to screen readers (essential for icon-only search or close buttons).
  • not-sr-only: reveals a “Skip to main content” link when keyboard users press Tab (sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4).
  • motion-reduce:transition-none and motion-reduce:animate-none: respects users who turned on Reduce Motion in macOS, iOS, or Windows.
  • print:hidden: hides navbars, sidebars, and footer clutter when someone prints your page.

Customizing your design system with @theme

In Tailwind v4, we no longer maintain a separate tailwind.config.js file. Every design token lives directly in CSS inside a @theme block.

When you add a variable inside @theme, Tailwind v4 automatically generates both the matching utility classes and standard CSS custom properties in :root:

@theme tokens--color-brand--color-paper--font-displayGenerates utilitiesbg-brand,text-brand,bg-paper,font-displayEmits CSS variablesvar(--color-brand)var(--color-paper)var(--font-display)

Let’s look at a clean design system file (src/app.css):

@import "tailwindcss";

@theme {
  --color-brand: #2563eb;
  --color-brand-dark: #1d4ed8;
  --color-paper: #faf9f6;

  --font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
  --font-display: "Instrument Serif", Georgia, serif;
  --font-mono: "Geist Mono", ui-monospace, monospace;

  --breakpoint-3xl: 120rem;
  --radius-card: 1rem;
}

Here is a real Tailwind CSS 4.3.5 build inspecting the exact CSS custom properties and utilities generated from that @theme block and a custom @utility (compiled in 20 ms):

Inspecting compiled @theme CSS custom properties and @utility output in Tailwind CSS 4.3.5

@theme namespaces at a glance

Prefix in @themeGenerated utility classesExample
--color-*bg-*, text-*, border-*, ring-*, fill-*--color-brand: #2563eb; → bg-brand
--font-*font-*--font-display: "Georgia", serif; → font-display
--text-*text-* (font sizes)--text-hero: 3.5rem; → text-hero
--spacing-*p-*, m-*, w-*, h-*, gap-*--spacing-sidebar: 16rem; → w-sidebar
--breakpoint-*Responsive prefixes (*:)--breakpoint-3xl: 120rem; → 3xl:grid-cols-4
--radius-*rounded-*--radius-card: 1rem; → rounded-card
--shadow-*shadow-*--shadow-card: 0 2px 8px rgb(0 0 0 / 0.08); → shadow-card
--animate-*animate-*--animate-fade-in: fade-in 200ms ease-out; → animate-fade-in

Adding custom web fonts

Load your .woff2 file with standard @font-face (or a Google Fonts <link> in <head>), then register the family inside @theme:

@import "tailwindcss";

@font-face {
  font-family: "Instrument Serif";
  src: url("/fonts/instrument-serif.woff2") format("woff2");
  font-weight: 400;
  font-display: swap;
}

@theme {
  --font-display: "Instrument Serif", Georgia, serif;
}

Replacing defaults vs extending them

By default, anything you put in @theme extends Tailwind’s built-in tokens. If your team wants a strict brand palette where nobody can accidentally use random pink-400 or lime-300 classes, reset that namespace first with initial:

@theme {
  --color-*: initial;
  --color-white: #ffffff;
  --color-ink: #111827;
  --color-muted: #6b7280;
  --color-brand: #2563eb;
}

Semantic light/dark tokens with @theme inline

When your theme token references another CSS variable that changes at runtime (for example, switching light and dark semantic colors on :root and .dark, or referencing next/font variables), add the inline keyword so Tailwind emits var(--surface) directly instead of baking the initial value in:

:root {
  --surface: #faf9f6;
  --ink: #0f172a;
}

.dark {
  --surface: #0b1120;
  --ink: #f8fafc;
}

@theme inline {
  --color-surface: var(--surface);
  --color-ink: var(--ink);
}

Now bg-surface text-ink adapts automatically between light and dark mode with zero dark: prefix repetition!

Custom utilities, variants, @layer, and @apply

Sometimes you want a custom helper class or element default that Tailwind does not ship out of the box.

Creating custom utilities with @utility

In Tailwind v4, declare custom utilities with @utility. Unlike a plain CSS class, a @utility automatically gains full support for hover:, md:, dark:, and focus-visible::

@utility content-auto {
  content-visibility: auto;
}

@utility scrollbar-none {
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

Now md:content-auto and scrollbar-none work right alongside built-in classes.

Custom element defaults with @layer base

Put global styles for raw HTML elements inside @layer base so utility classes can still override them cleanly:

@layer base {
  body {
    background-color: var(--color-paper);
    color: var(--color-slate-900);
  }

  a {
    color: var(--color-brand);
  }
}

My honest take on @apply

Tailwind lets you compose utility classes inside a traditional CSS rule using @apply:

@layer components {
  .btn-primary {
    @apply inline-flex items-center justify-center rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand-dark;
  }
}

I used @apply a lot when I first learned Tailwind, and then I stopped.

Why? Because extracting a real template component (an Astro <Button.astro>, React <Button />, Laravel <x-button>, or Rails partial) gives you one reusable source of truth for both markup and classes without inventing a parallel CSS naming system again.

Keep @apply for places where you cannot edit the HTML directly (like third-party library widgets or rendered Markdown) and prefer real components everywhere else.

Styling forms, tables, and Markdown prose

Forms, data tables, and long-form articles are where many Tailwind sites either shine or fall apart. Let’s make sure each of them looks sharp out of the box.

Clean, accessible forms

<form class="max-w-md space-y-5">
  <div>
    <label for="email" class="block text-sm font-medium text-slate-700 dark:text-slate-200">
      Email address
    </label>
    <input
      id="email"
      type="email"
      required
      placeholder="flavio@flaviocopes.com"
      class="mt-1.5 block w-full rounded-lg border border-slate-300 bg-white px-3.5 py-2 text-sm text-slate-900 shadow-2xs placeholder:text-slate-400 focus:border-blue-500 focus:ring-3 focus:ring-blue-500/20 focus:outline-hidden user-invalid:border-red-500 dark:border-slate-700 dark:bg-slate-900 dark:text-white"
    />
  </div>

  <div>
    <label for="avatar" class="block text-sm font-medium text-slate-700 dark:text-slate-200">
      Profile photo
    </label>
    <input
      id="avatar"
      type="file"
      accept="image/*"
      class="mt-1.5 block w-full text-sm text-slate-600 file:mr-4 file:rounded-lg file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-semibold file:text-blue-700 hover:file:bg-blue-100"
    />
  </div>

  <label class="flex items-center gap-2.5 text-sm text-slate-700 dark:text-slate-300">
    <input type="checkbox" class="size-4 rounded accent-blue-600" />
    Send me new handbook releases
  </label>

  <button
    type="submit"
    class="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white shadow-xs hover:bg-blue-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600"
  >
    Join newsletter
  </button>
</form>

Notice three handy form utilities here:

  • accent-blue-600 tints native checkboxes, radios, and range sliders in one class.
  • file:* styles the ugly browser file-picker button cleanly.
  • user-invalid:border-red-500 highlights invalid fields only after the user edits or submits them (never on initial empty page load!).

Responsive data tables

Always wrap tables in overflow-x-auto so narrow mobile screens scroll the table horizontally instead of breaking the whole page layout:

<div class="overflow-x-auto rounded-xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900">
  <table class="min-w-full divide-y divide-slate-200 text-left text-sm dark:divide-slate-800">
    <thead class="bg-slate-50 text-xs font-semibold tracking-wider text-slate-500 uppercase dark:bg-slate-950/60">
      <tr>
        <th class="px-5 py-3">Handbook</th>
        <th class="px-5 py-3">Format</th>
        <th class="px-5 py-3 text-right">Pages</th>
      </tr>
    </thead>
    <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
      <tr class="hover:bg-slate-50/80 dark:hover:bg-slate-800/50">
        <td class="px-5 py-3.5 font-medium text-slate-900 dark:text-white">TypeScript Handbook</td>
        <td class="px-5 py-3.5 text-slate-600 dark:text-slate-300">PDF + EPUB</td>
        <td class="px-5 py-3.5 text-right font-mono tabular-nums">43</td>
      </tr>
      <tr class="hover:bg-slate-50/80 dark:hover:bg-slate-800/50">
        <td class="px-5 py-3.5 font-medium text-slate-900 dark:text-white">Tailwind CSS Handbook</td>
        <td class="px-5 py-3.5 text-slate-600 dark:text-slate-300">PDF + EPUB</td>
        <td class="px-5 py-3.5 text-right font-mono tabular-nums">40</td>
      </tr>
    </tbody>
  </table>
</div>

Long-form Markdown with @tailwindcss/typography

Because Preflight strips heading and list styles, rendered Markdown looks completely flat until you style it.

Install the official typography plugin and enable it with @plugin in src/app.css:

npm install -D @tailwindcss/typography
@import "tailwindcss";
@plugin "@tailwindcss/typography";

Wrap your rendered Markdown HTML in prose:

<article class="prose prose-slate dark:prose-invert mx-auto max-w-2xl prose-headings:tracking-tight prose-a:text-blue-600 prose-img:rounded-xl">
  <!-- Rendered Markdown HTML goes here -->
</article>

Element modifiers like prose-a:text-blue-600, prose-code:before:content-none, and prose-img:rounded-xl let you fine-tune the typography plugin without overriding CSS selectors manually.

Transitions, transforms, and modern animations

Subtle motion makes buttons and cards feel responsive without getting in the reader’s way.

Everyday transitions and transforms

Pick narrow transition properties (transition-colors, transition-transform, transition-opacity) instead of transition-all so the browser stays fast and never animates unexpected layout shifts:

<a
  href="/ebooks"
  class="block rounded-xl border border-slate-200 bg-white p-6 transition duration-200 ease-out hover:-translate-y-0.5 hover:border-slate-300 hover:shadow-md motion-reduce:transition-none motion-reduce:hover:translate-y-0"
>
  <h3 class="font-semibold text-slate-900">Browse all handbooks</h3>
  <p class="mt-1 text-sm text-slate-600">Free PDF and EPUB guides for web developers.</p>
</a>

Built-in animations and custom @keyframes

Tailwind ships four handy built-in animations:

  • animate-spin (loading spinners)
  • animate-pulse (skeleton loading placeholders)
  • animate-ping (live status indicator dot)
  • animate-bounce (scroll-down cue)

Add your own animation cleanly inside @theme:

@theme {
  --animate-fade-up: fade-up 250ms ease-out both;

  @keyframes fade-up {
    from {
      opacity: 0;
      transform: translateY(8px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}

Then apply animate-fade-up motion-reduce:animate-none anywhere in your HTML.

Entry animations with starting: (@starting-style)

One of the coolest additions in Tailwind v4 is the starting: variant, powered by CSS @starting-style.

Previously, fading in a native <dialog> or [popover] when it switched from display: none to display: block required JavaScript timers. Now it takes one class string:

<div
  id="tip-popover"
  popover
  class="rounded-xl border border-slate-200 bg-white p-4 shadow-lg transition duration-200 open:opacity-100 open:scale-100 starting:open:opacity-0 starting:open:scale-95"
>
  Smooth entry animation with zero JavaScript!
</div>

Complete project: building a responsive landing and pricing page

Let’s put everything we learned together by building a complete, production-ready storefront page (BookShelf, an independent developer ebook library) from scratch using Tailwind CSS v4.

Step 1: Set up the tokens in src/app.css

We declare our brand palette, semantic paper surface, font stack, and class-based dark mode toggle in one short file:

@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));

@theme {
  --color-brand: #2563eb;
  --color-brand-dark: #1d4ed8;
  --color-paper: #faf9f6;
  --font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
  --font-mono: "Geist Mono", ui-monospace, monospace;
}

@layer base {
  html {
    color-scheme: light dark;
  }
}

Step 2: Sticky frosted-glass navbar

<header class="sticky top-0 z-30 border-b border-slate-200/80 bg-paper/85 backdrop-blur-md dark:border-slate-800 dark:bg-slate-950/85">
  <div class="mx-auto flex max-w-6xl items-center justify-between px-6 py-4">
    <a href="/" class="flex items-center gap-2 font-mono text-base font-bold tracking-tight text-slate-900 dark:text-white">
      <span class="size-2.5 rounded-full bg-brand"></span>
      BookShelf
    </a>

    <nav class="hidden items-center gap-7 text-sm font-medium text-slate-600 md:flex dark:text-slate-300">
      <a href="#features" class="hover:text-slate-900 dark:hover:text-white">Features</a>
      <a href="#pricing" class="hover:text-slate-900 dark:hover:text-white">Pricing</a>
      <a href="#newsletter" class="hover:text-slate-900 dark:hover:text-white">Newsletter</a>
    </nav>

    <a
      href="#pricing"
      class="rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-slate-900 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-200"
    >
      Get access
    </a>
  </div>
</header>

Step 3: Centered hero section

<section class="mx-auto max-w-4xl px-6 pt-20 pb-16 text-center md:pt-28">
  <p class="inline-flex items-center gap-2 rounded-full border border-blue-200 bg-blue-50 px-3.5 py-1 text-xs font-semibold text-blue-700 dark:border-blue-900 dark:bg-blue-950/60 dark:text-blue-300">
    Updated for Tailwind CSS v4.3
  </p>

  <h1 class="mt-6 text-4xl/tight font-bold tracking-tight text-balance text-slate-900 sm:text-5xl/tight md:text-6xl/tight dark:text-white">
    Practical developer handbooks you can finish in a weekend
  </h1>

  <p class="mx-auto mt-6 max-w-2xl text-lg/relaxed text-pretty text-slate-600 dark:text-slate-300">
    Skip thousand-page textbooks. Every handbook starts from zero, sticks to real runnable code, and ships in PDF (A4 and US Letter) plus EPUB.
  </p>

  <div class="mt-8 flex flex-col items-center justify-center gap-3 sm:flex-row">
    <a
      href="#pricing"
      class="w-full rounded-lg bg-brand px-6 py-3 text-sm font-semibold text-white shadow-xs transition-colors hover:bg-brand-dark sm:w-auto"
    >
      Browse the library
    </a>
    <a
      href="#features"
      class="w-full rounded-lg border border-slate-300 bg-white px-6 py-3 text-sm font-semibold text-slate-700 transition-colors hover:bg-slate-50 sm:w-auto dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"
    >
      See what is inside
    </a>
  </div>
</section>

Step 4: Feature grid with @container cards

<section id="features" class="mx-auto max-w-6xl px-6 py-16">
  <div class="grid grid-cols-1 gap-6 md:grid-cols-3">
    <div class="@container">
      <article class="flex h-full flex-col gap-3 rounded-2xl border border-slate-200 bg-white p-6 shadow-2xs @sm:p-7 dark:border-slate-800 dark:bg-slate-900">
        <span class="font-mono text-xs font-semibold text-brand uppercase">01 / Formats</span>
        <h2 class="text-lg font-semibold text-slate-900 dark:text-white">A4, US Letter, and EPUB</h2>
        <p class="text-sm/relaxed text-slate-600 dark:text-slate-300">
          Read on Kindle, Apple Books, iPad, or print clean 14pt pages on either European A4 or US Letter paper.
        </p>
      </article>
    </div>

    <div class="@container">
      <article class="flex h-full flex-col gap-3 rounded-2xl border border-slate-200 bg-white p-6 shadow-2xs @sm:p-7 dark:border-slate-800 dark:bg-slate-900">
        <span class="font-mono text-xs font-semibold text-brand uppercase">02 / Verified</span>
        <h2 class="text-lg font-semibold text-slate-900 dark:text-white">Real runnable examples</h2>
        <p class="text-sm/relaxed text-slate-600 dark:text-slate-300">
          Every code snippet, terminal command, and output is tested live against current tools instead of recycled docs.
        </p>
      </article>
    </div>

    <div class="@container">
      <article class="flex h-full flex-col gap-3 rounded-2xl border border-slate-200 bg-white p-6 shadow-2xs @sm:p-7 dark:border-slate-800 dark:bg-slate-900">
        <span class="font-mono text-xs font-semibold text-brand uppercase">03 / Beginner-first</span>
        <h2 class="text-lg font-semibold text-slate-900 dark:text-white">One concept at a time</h2>
        <p class="text-sm/relaxed text-slate-600 dark:text-slate-300">
          Chapters build in strict prerequisite order so you never hit jargon before learning the fundamentals first.
        </p>
      </article>
    </div>
  </div>
</section>

Step 5: Two-tier pricing cards with tabular-nums

<section id="pricing" class="mx-auto max-w-4xl px-6 py-16">
  <div class="text-center">
    <h2 class="text-3xl font-bold tracking-tight text-slate-900 dark:text-white">Simple pricing</h2>
    <p class="mt-2 text-slate-600 dark:text-slate-300">Start free, upgrade only if you want workshops.</p>
  </div>

  <div class="mt-10 grid grid-cols-1 gap-6 md:grid-cols-2">
    <div class="flex flex-col rounded-2xl border border-slate-200 bg-white p-8 dark:border-slate-800 dark:bg-slate-900">
      <h3 class="text-lg font-semibold text-slate-900 dark:text-white">Free Library</h3>
      <p class="mt-2 text-sm text-slate-600 dark:text-slate-300">Every programming handbook in PDF and EPUB.</p>
      <p class="mt-6 text-4xl font-bold tracking-tight text-slate-900 tabular-nums dark:text-white">$0</p>
      <ul class="mt-6 flex-1 space-y-2.5 text-sm text-slate-600 dark:text-slate-300">
        <li>All 46 developer handbooks</li>
        <li>A4, US Letter, and EPUB downloads</li>
        <li>Lifetime updates when new versions ship</li>
      </ul>
      <a
        href="/download/"
        class="mt-8 block rounded-lg border border-slate-300 px-4 py-2.5 text-center text-sm font-semibold text-slate-900 hover:bg-slate-50 dark:border-slate-700 dark:text-white dark:hover:bg-slate-800"
      >
        Download free books
      </a>
    </div>

    <div class="flex flex-col rounded-2xl border-2 border-brand bg-white p-8 shadow-md dark:bg-slate-900">
      <div class="flex items-center justify-between">
        <h3 class="text-lg font-semibold text-slate-900 dark:text-white">Pro Workshops</h3>
        <span class="rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-semibold text-brand dark:bg-blue-950">
          Popular
        </span>
      </div>
      <p class="mt-2 text-sm text-slate-600 dark:text-slate-300">Hands-on projects, video walkthroughs, and community.</p>
      <p class="mt-6 text-4xl font-bold tracking-tight text-slate-900 tabular-nums dark:text-white">$99</p>
      <ul class="mt-6 flex-1 space-y-2.5 text-sm text-slate-600 dark:text-slate-300">
        <li>Everything in Free Library</li>
        <li>Complete real-world project repos</li>
        <li>Direct Q&A and code reviews</li>
      </ul>
      <a
        href="/courses/"
        class="mt-8 block rounded-lg bg-brand px-4 py-2.5 text-center text-sm font-semibold text-white hover:bg-brand-dark"
      >
        Explore workshops
      </a>
    </div>
  </div>
</section>
<section id="newsletter" class="mx-auto max-w-3xl px-6 py-16">
  <div class="rounded-2xl border border-slate-200 bg-white p-8 text-center shadow-2xs dark:border-slate-800 dark:bg-slate-900">
    <h2 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">Get new handbooks first</h2>
    <p class="mt-2 text-sm text-slate-600 dark:text-slate-300">One practical email per week. Unsubscribe in one click.</p>
    <form class="mx-auto mt-6 flex max-w-md flex-col gap-3 sm:flex-row">
      <label for="nl-email" class="sr-only">Email address</label>
      <input
        id="nl-email"
        type="email"
        required
        placeholder="you@domain.com"
        class="min-w-0 flex-1 rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-sm text-slate-900 placeholder:text-slate-400 focus:border-brand focus:ring-3 focus:ring-blue-500/20 focus:outline-hidden dark:border-slate-700 dark:bg-slate-950 dark:text-white"
      />
      <button
        type="submit"
        class="shrink-0 rounded-lg bg-brand px-5 py-2.5 text-sm font-semibold text-white hover:bg-brand-dark"
      >
        Subscribe
      </button>
    </form>
  </div>
</section>

Compile that entire landing page with npx @tailwindcss/cli -i src/app.css -o dist/app.css --minify, and the whole production stylesheet lands under 4 KB gzipped with dark mode, responsive grids, container queries, and focus states included!

Real-world workflow, pitfalls, and upgrading from v3

Once you use Tailwind on production apps for a few weeks, five practical habits save hours of debugging.

1. Never construct class names dynamically with string interpolation

This is the #1 Tailwind mistake. Because Oxide scans your source files as static plain text without running JavaScript, dynamically glued strings are invisible to the scanner:

// BROKEN: Tailwind never sees "bg-red-600" or "bg-emerald-600" in source code
const badgeClass = `bg-${color}-600 text-white`

Always write complete, unbroken class strings inside a lookup map:

const BADGE_CLASSES = {
  error: 'bg-red-600 text-white',
  success: 'bg-emerald-600 text-white',
  info: 'bg-blue-600 text-white',
}

const badgeClass = BADGE_CLASSES[status]

I cover this in detail in Tailwind CSS cannot generate classes dynamically.

2. Scanning shared UI packages in monorepos (@source)

Tailwind v4 ignores node_modules and gitignored folders by default. If your app imports components from a sibling workspace package or external folder, register it with @source right inside src/app.css:

@import "tailwindcss";
@source "../packages/ui/src";

3. Merging conflicting props in reusable components (tailwind-merge)

Suppose you write a <Button className="bg-blue-600 px-4 py-2" /> component in React or Astro that accepts an extra class prop, and a caller passes <Button class="bg-red-600" />.

In CSS, whichever class appears later in the generated stylesheet wins, not whichever came second in the HTML class string!

Combine clsx and tailwind-merge into a 4-line cn() helper so caller overrides always win predictably:

import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

cn('bg-blue-600 px-4 py-2', 'bg-red-600')
// 'px-4 py-2 bg-red-600'

4. Automatic class sorting with Prettier

Stop debating class order in code reviews. Install prettier-plugin-tailwindcss:

npm install -D prettier prettier-plugin-tailwindcss

Every time you save a file, Prettier sorts utility classes into Tailwind’s recommended order (layout → spacing → sizing → typography → colors → borders → states) automatically.

5. Upgrading a Tailwind v3 project to v4

Run Tailwind’s official automated upgrade CLI on a clean git branch:

npx @tailwindcss/upgrade

Review the diff and check these five common v3-to-v4 renames:

Tailwind v3Tailwind v4Why it changed
shadow-sm / shadowshadow-xs / shadow-smScale shifted down one step for softer defaults
rounded-sm / roundedrounded-xs / rounded-smMatches the updated 2xs/xs/sm naming
bg-gradient-to-rbg-linear-to-rAligns with bg-radial and bg-conic
outline-noneoutline-hiddenKeeps accessible outlines in Windows Forced Colors mode
!flexflex!Trailing ! avoids conflicts with other syntax
border (default gray)border border-slate-200Default border color is now currentColor

CSS-to-Tailwind quick reference

Keep these lookup tables open whenever you know the CSS property you want and need its Tailwind v4 class name fast.

Spacing, sizing, and layout

CSS propertyTailwind v4 utilitiesExample
paddingp-*, px-*, py-*, pt-*, pr-*, pb-*, pl-*, ps-*, pe-*px-6 py-4
marginm-*, mx-auto, my-*, mt-*, -mt-*mx-auto mt-8
width / heightw-*, h-*, size-*, min-w-*, max-w-*, min-h-dvhw-full max-w-2xl size-10
displayblock, inline-block, flex, inline-flex, grid, hiddenhidden md:flex
overflowoverflow-hidden, overflow-auto, overflow-x-autooverflow-x-auto
aspect-ratioaspect-square, aspect-video, aspect-4/3aspect-video
positionrelative, absolute, fixed, sticky, inset-0, top-0, z-20sticky top-0 z-20

Typography and colors

CSS propertyTailwind v4 utilitiesExample
font-familyfont-sans, font-serif, font-monofont-mono
font-size / line-heighttext-xs..text-6xl, text-base/7, leading-relaxedtext-3xl/tight
font-weightfont-normal, font-medium, font-semibold, font-boldfont-semibold
text-align / text-wraptext-left, text-center, text-right, text-balance, text-prettytext-balance
font-variant-numerictabular-nums, lining-numstabular-nums
color / background-colortext-*, bg-*, bg-blue-600/15, bg-[#faf9f6]bg-slate-900 text-white
background-imagebg-linear-to-r, bg-radial, from-*, via-*, to-*bg-linear-to-r from-blue-600 to-indigo-600

Flexbox, Grid, borders, and effects

CSS propertyTailwind v4 utilitiesExample
flex-direction / flex-wrapflex-row, flex-col, flex-wrapflex flex-col gap-4
align-items / justify-contentitems-center, items-start, justify-between, justify-centeritems-center justify-between
flex / flex-shrinkflex-1, flex-none, shrink-0, growmin-w-0 flex-1
grid-template-columnsgrid-cols-1..12, grid-cols-[240px_1fr], grid-cols-subgridgrid grid-cols-1 md:grid-cols-3
gapgap-*, gap-x-*, gap-y-*gap-6
border / border-radiusborder, border-t, border-slate-200, divide-y, rounded-xlrounded-xl border border-slate-200
box-shadow / backdrop-filtershadow-xs, shadow-sm, shadow-md, backdrop-blur-mdshadow-sm backdrop-blur-md
transition / transformtransition-colors, duration-200, hover:-translate-y-0.5, scale-95transition duration-200

Where to go from here

You now know every piece of Tailwind CSS v4 you need to build real web apps from a blank HTML file to a customized, dark-mode-ready design system.

My advice is to open a small side project today, install @tailwindcss/vite or @tailwindcss/cli, set up three @theme tokens, and build one full screen without writing a single custom CSS class. After two or three sessions, the utility names become muscle memory.

To sharpen your HTML and CSS foundations alongside Tailwind, read my free CSS Handbook, HTML Handbook, and HTML Forms Handbook, and try the interactive Tailwind cheat sheet and converter on the online Tailwind CSS guide.

CSS-to-Tailwind quick reference

Search and filter the most common Tailwind CSS v4 utilities right here in your browser:

Tailwind cheat sheetInteractive · runs in your browser

Category

Curated common utilities for Tailwind v4 defaults — not every generated class. Scale values (p-5, w-72, …) follow the same pattern as the listed examples.

Utilities

No utilities match that filter.

ClassCSSCategory
Tailwind to CSSInteractive · runs in your browser

Supported subset (rule-based)

Not a full Tailwind compiler — plugins, custom theme tokens, and many advanced utilities will show as unsupported.

Paste classes or load the example to see CSS output.

No supported classes mapped yet — see unsupported warnings below.

CSS output

Per-class mappings

ClassCSSNote

Unsupported warnings

These classes are outside the supported subset — keep them as Tailwind or write custom CSS.

Want me to talk about your product? You can sponsor this site.

Related posts about css: