Tailwind CSS

1. Utility-First CSS: Core Idea

Traditional CSS:

.card {
  padding: 1.5rem;
  border-radius: 0.75rem;
  background-color: white;
  box-shadow: 0 4px 6px rgb(0 0 0 / 0.1);
}
<div class="card">Content</div>

Tailwind:

<div className="rounded-xl bg-white p-6 shadow-md">Content</div>

Common Utility Classes:

Classfunction
p-4Padding
m-4Margin
flexdisplay: flex
griddisplay: grid
rounded-lgBorder Radius
bg-blue-500Background Color
text-lgFont Size
font-boldFont Weight
shadow-mdBox Shadow
hiddendisplay: none

Main features of Tailwind:

  • Combine styles directly in JSX.
  • Use unified design scales such as Spacing, Color, Typography, etc.
  • Built-in responsive and interactive state variants.
  • Generate CSS based on Class used in the project source code.
  • Suitable for UI reuse via React Component package.

Tailwind does not replace the fundamentals of CSS, and Box Model, Flexbox, Grid, Positioning, and CSS Cascade still need to be understood.

2. Installation and integration with Next.js

Tailwind CSS v4 is recommended to be integrated through the PostCSS or Vite plug-ins.

For Next.js:

npm install tailwindcss @tailwindcss/postcss postcss

Configure postcss.config.mjs:

const config = {
  plugins: {
    "@tailwindcss/postcss": {},
  },
};

export default config;

Import in app/globals.css:

@import "tailwindcss";

Introduced in root Layout:

// app/layout.tsx

import "./globals.css";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

Then you can use:

export default function HomePage() {
  return (
    <main className="mx-auto max-w-4xl p-6">
      <h1 className="text-3xl font-bold">Hello Tailwind</h1>
    </main>
  );
}

Important changes to Tailwind CSS v4

Compared to v3:

  • Use @import "tailwindcss".
  • More emphasis on CSS-first Configuration.
  • Define Design Tokens by @theme.
  • Utility Classes in the project is automatically detected by default.
  • It is generally no longer necessary to create tailwind.config.js separately.

v3's @tailwind base;, @tailwind components; and @tailwind utilities; are no longer the recommended import methods for v4.

3. Spacing: spacing

Tailwind provides a unified set of Spacing Scale.

<div className="m-4 p-6">Content</div>

Commonly used prefixes:

Classmeaning
p-*Padding
px-*Level Padding
py-*Vertical Padding
pt-* / pb-*Up / Down Padding
m-*Margin
mx-* / my-*Horizontal / vertical Margin
mt-* / mb-*Up / Down Margin
gap-*Flex/Grid sub-element spacing
space-y-*vertical spacing between adjacent child elements

Default Spacing Scale:

1  → 0.25rem
2  → 0.5rem
4  → 1rem
6  → 1.5rem
8  → 2rem

Therefore:

<div className="p-4 mt-6 gap-2">

Roughly corresponds to:

padding: 1rem;
margin-top: 1.5rem;
gap: 0.5rem;

Center horizontally

<div className="mx-auto max-w-5xl px-4">Content</div>

Here:

  • mx-auto: left and right automatic Margin.
  • max-w-5xl: Limit the maximum width.
  • px-4: Guarantee padding on both sides.

This is a very common combination in web content containers.

4. Width, Height and Display

width and height

<div className="w-full max-w-xl min-h-screen">Content</div>

Commonly used Class:

Classfunction
w-fullWidth 100%
w-1/2Width 50%
w-screenviewport width
max-w-lgmaximum width
h-fullheight 100%
h-screenviewport height
min-h-screenThe minimum height is the viewport height
size-10Set width and height at the same time
aspect-video16:9 aspect ratio

Display

<div className="block">Block</div>
<div className="inline-block">Inline Block</div>
<div className="flex">Flex</div>
<div className="grid">Grid</div>
<div className="hidden">Hidden</div>

In particular, it is necessary to distinguish:

  • hidden: The element does not participate in layout.
  • invisible: The element is invisible but still occupies layout space.
  • opacity-0: The element is transparent, but may still respond to interactions.

5. Flexbox: Flexible layout

Flexbox is one of the most commonly used layout methods of Tailwind.

Arrange horizontally

<div className="flex items-center justify-between gap-4">
  <span>Logo</span>
  <nav>Navigation</nav>
</div>

Commonly used Class:

Classcorresponding concept
flexFlex Container
flex-rowArrange horizontally
flex-colvertical arrangement
items-centerCross Axis Centered
justify-centerMain Axis Centered
justify-betweenAlign both ends of the spindle
gap-4element spacing
flex-wrapAllow line breaks
flex-1Occupies allocable space
shrink-0no shrinkage allowed
growallowed to grow

Center horizontally and vertically

<div className="flex min-h-screen items-center justify-center">
  <div>Centered Content</div>
</div>

two column layout

<div className="flex gap-6">
  <aside className="w-64 shrink-0">Sidebar</aside>

  <main className="min-w-0 flex-1">Main Content</main>
</div>

min-w-0 is useful in Flex Layout to prevent longer content from preventing Flex Item from shrinking properly.

6. Grid: Grid layout

Grid is more suitable for two-dimensional layouts, such as card lists, Dashboard.

Basic Grid

<div className="grid grid-cols-3 gap-4">
  <div>Card A</div>
  <div>Card B</div>
  <div>Card C</div>
</div>

Commonly used Class:

Classfunction
gridGrid Container
grid-cols-2two columns
grid-cols-3three columns
grid-cols-12Twelve columns
col-span-2span two columns
row-span-2across two lines
gap-4spacing between rows and columns
gap-x-4column spacing
gap-y-4line spacing

Common card layouts

<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
  <Card />
  <Card />
  <Card />
</div>

One column for mobile, two columns for medium screens, and three columns for large screens.

Choice of Flexbox and Grid

  • Flexbox: More suitable for one-dimensional arrangements, such as navigation bars, button groups, and toolbars.
  • Grid: More suitable for two-dimensional layouts, such as card grid, Dashboard.

7. Responsive Design: Responsive design

Tailwind uses the responsive design mechanism of Mobile-First.

Default breakpoint:

Prefixminimum width
sm:640px
md:768px
lg:1024px
xl:1280px
2xl:1536px

For example:

<div className="text-sm md:text-base lg:text-lg">Responsive Text</div>

means:

  • Default: text-sm.
  • The width reaches md: text-base.
  • The width reaches lg: text-lg.

Note: sm: is not just for mobile phones, but means 640px and above.

Responsive layout

<div className="flex flex-col gap-4 md:flex-row">
  <aside className="w-full md:w-64">Sidebar</aside>

  <main className="flex-1">Content</main>
</div>

Responsive show and hide

<div className="hidden md:block">
  Desktop Navigation
</div>

<div className="block md:hidden">
  Mobile Navigation
</div>

Container Queries

Tailwind v4 also supports CSS Container Queries, which determines the style based on the parent container size rather than the entire Viewport.

<div className="@container">
  <div className="flex flex-col @md:flex-row">
    <div>Content</div>
  </div>
</div>

For reused components, Container Queries is sometimes more appropriate than Viewport Breakpoints.

8. Typography: text style

Common Typography Utility Classes:

Classfunction
text-smFont size
text-xlFont size
font-mediumFont weight
font-semiboldsemi-thick
font-boldBold
text-centerCenter text
text-gray-600text color
leading-relaxedrow height
tracking-wideword spacing
truncateSingle line truncation
break-wordsWrap long words

Example:

<article>
  <h1 className="text-3xl font-bold tracking-tight">Article Title</h1>

  <p className="mt-4 text-base leading-7 text-gray-600">Article description.</p>
</article>

If you need to render the text of articles such as Markdown and MDX that contain a large number of nested HTML, you can consider the prose style provided by the @tailwindcss/typography plug-in.

It is different from the ordinary Utility-First component style and is mainly designed for long rich text.

9. Background, Border and Shadow

color

<div className="bg-blue-500 text-white">Content</div>

Color classes usually use:

bg-{color}-{shade}
text-{color}-{shade}
border-{color}-{shade}

For example:

<div className="border border-gray-200 bg-white text-gray-900">Content</div>

Border and Radius

<div className="rounded-xl border border-gray-200">Card</div>

Common Class:

  • border、border-2。
  • border-gray-300。
  • rounded-md、rounded-lg、rounded-xl。
  • rounded-full。

Shadow

<div className="rounded-lg bg-white p-6 shadow-md">Card</div>

Common levels:

shadow-sm
shadow
shadow-md
shadow-lg
shadow-xl

Shadows, borders, and rounded corners are often used in combination, but don’t overlay all components with too much decoration.

10. Variants: Status style

Tailwind Use Variant Prefix to express interaction status or environmental conditions.

Hover、Focus、Active

<button
  className="
    rounded-lg bg-blue-600 px-4 py-2 text-white
    hover:bg-blue-700
    focus-visible:outline-2
    focus-visible:outline-offset-2
    focus-visible:outline-blue-600
    active:bg-blue-800
    disabled:cursor-not-allowed
    disabled:opacity-50
  "
>
  Save
</button>

Common Variant:

Variantfunction
hover:mouseover
focus:get focus
focus-visible:When focus prompts need to be displayed
active:active state
disabled:disabled state
checked:Checkbox selected
first: / last:first/last child element
odd: / even:odd and even elements
aria-*:ARIA attribute matching
data-*:Data Attribute match

These Variant are essentially used to generate style rules with CSS Pseudo-class, Attribute Selector or Media Query.

Group

Change child elements based on parent element state:

<div className="group rounded-lg p-4 hover:bg-gray-100">
  <h3 className="text-gray-900 group-hover:text-blue-600">Title</h3>
</div>

Peer

Change styles based on the status of sibling elements:

<div>
  <input type="checkbox" className="peer" id="agree" />

  <label
    htmlFor="agree"
    className="ml-2 text-gray-500 peer-checked:text-green-600"
  >
    Agree
  </label>
</div>

group-* and peer-* are more commonly used state association mechanisms that reduce the need to write JavaScript for purely style interactions.

11. Dark Mode: Dark mode

Tailwind supports dark: Variant:

<div className="bg-white text-gray-900 dark:bg-gray-900 dark:text-white">
  Content
</div>

By default, dark: takes effect based on the system prefers-color-scheme media query.

If you want to use .dark Class to switch manually, you can define it in Tailwind v4:

@import "tailwindcss";

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

Then:

<html class="dark"></html>

The corresponding dark:* style will take effect.

For the Next.js project, if you need theme switching, persistence settings, SSR and avoiding page flickering, you can use schemes such as next-themes to handle the theme state instead of letting Tailwind manage the state directly.

Tailwind is responsible for style rules, and the theme state is managed by application logic.

12. Theme:Design Tokens

Tailwind CSS v4 uses CSS-first Configuration.

Project design variables can be customized via @theme:

@import "tailwindcss";

@theme {
  --color-brand-500: #2563eb;
  --color-brand-600: #1d4ed8;

  --font-display: "Inter", sans-serif;

  --radius-card: 0.75rem;
}

Then use the corresponding Utility:

<button className="rounded-card bg-brand-500 px-4 py-2 font-display text-white hover:bg-brand-600">
  Submit
</button>

Theme Variables can be defined:

  • color.
  • font.
  • breakpoint.
  • spacing.
  • Rounded corners.
  • shadow.
  • animation parameters.

Ordinary CSS Variables and @theme

There is a difference between the two.

Normal CSS Variable:

:root {
  --my-custom-color: #2563eb;
}

Mainly used for reuse in CSS:

.button {
  color: var(--my-custom-color);
}

Tailwind Theme Variable:

@theme {
  --color-brand-500: #2563eb;
}

Tailwind Utility can be additionally generated, for example:

<div className="text-brand-500">

Therefore, in a Tailwind project, it is common to place design variables that you wish to map to Utility Classes into @theme.

13. Arbitrary Values: any value

Tailwind allows the use of square brackets to specify values that are not in the default design scale.

<div className="w-[350px]">Content</div>

Other examples:

<div className="h-[calc(100vh-64px)]" />

<div className="bg-[#1e293b]" />

<div className="grid grid-cols-[240px_1fr]" />

You can also use the CSS property via Arbitrary Property:

<div className="[scrollbar-width:thin]">Content</div>

Arbitrary Variants

Apply styles to specific descendant elements:

<div className="[&_p]:mb-4 [&_a]:text-blue-600">
  <p>Paragraph</p>
  <a href="/">Link</a>
</div>

Among them, & represents the current element, and _ can represent spaces in this type of selector syntax.

These functions are flexible, but heavy use of arbitrary values may mean that the project lacks a unified Design Tokens.

14. @apply and custom CSS

Tailwind allows reusing an existing Utility in CSS:

.button-primary {
  @apply rounded-lg bg-blue-600 px-4 py-2 font-medium text-white;
}

Then:

<button className="button-primary">Submit</button>

However, it is not recommended to repackage all Tailwind Class into CSS Class, otherwise the directness of Utility-First may be lost.

@utility

Tailwind v4 supports custom Utility:

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

Use:

<div className="content-auto">Content</div>

It can also be used with Variant:

<div className="lg:content-auto">Content</div>

The CSS behavior is suitable for repeated use in the project and does not belong to the existing Tailwind Utility.

15. Class combination in React

For React projects, usually you should not rewrite all the styles of reusable components at the calling point.

Component Extraction

type ButtonProps = {
  children: React.ReactNode;
  onClick?: () => void;
};

function Button({ children, onClick }: ButtonProps) {
  return (
    <button
      onClick={onClick}
      className="rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
    >
      {children}
    </button>
  );
}

Condition Class

function Badge({ active }: { active: boolean }) {
  return (
    <span
      className={
        active
          ? "rounded bg-green-100 px-2 py-1 text-green-700"
          : "rounded bg-gray-100 px-2 py-1 text-gray-600"
      }
    >
      Status
    </span>
  );
}

clsx

When there are many conditions, you can use clsx:

npm install clsx
import clsx from "clsx";

function Button({ disabled }: { disabled: boolean }) {
  return (
    <button
      disabled={disabled}
      className={clsx(
        "rounded-lg px-4 py-2",
        disabled
          ? "cursor-not-allowed bg-gray-300"
          : "bg-blue-600 text-white hover:bg-blue-700",
      )}
    >
      Submit
    </button>
  );
}

tailwind-merge

Tailwind Class When there is a conflict, for example:

p-2 p-4

Can be merged via tailwind-merge:

import { twMerge } from "tailwind-merge";

twMerge("p-2 p-4"); // "p-4"

Common cn() helper functions:

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

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

This is also a common Class combination in shadcn/ui and other React component solutions.

16. Class Detection and construction mechanism

Tailwind will scan the Utility Class that appears in the source code and generate the corresponding CSS.

React / JSX / HTML
        ↓
Tailwind Source Detection
        ↓
Identify Utility Classes
        ↓
Generate CSS
        ↓
Browser

Avoid dynamic splicing Class Name

Not recommended:

function Button({ color }: { color: string }) {
  return <button className={`bg-${color}-500`}>Button</button>;
}

Source code inspection for Tailwind often does not reliably identify this type of runtime string concatenation.

It is recommended to use the complete static Class:

const colorClasses = {
  blue: "bg-blue-500 hover:bg-blue-600",
  red: "bg-red-500 hover:bg-red-600",
};

function Button({ color }: { color: keyof typeof colorClasses }) {
  return <button className={colorClasses[color]}>Button</button>;
}

@source

Tailwind v4 will automatically detect common project source codes; if some external directories are not scanned, you can specify them explicitly:

@import "tailwindcss";

@source "../node_modules/@my-company/ui";

This is useful in Monorepo or shared UI Package.

17. The relationship between Tailwind and CSS Modules, shadcn/ui

Tailwind and CSS Modules

There is no conflict between the two.

Tailwind suitable for:

  • Everyday component styles.
  • Responsive design.
  • interaction status.
  • Unified Design Tokens.

CSS Modules suitable for:

  • Complex CSS Selector.
  • Special animation.
  • Patterns that are difficult to express using Utility.
  • Partially isolated custom CSS.

Projects can be used simultaneously:

import styles from "./Map.module.css";

<div className={`${styles.mapContainer} rounded-lg border`}>Map</div>;

Tailwind and shadcn/ui

Need to distinguish:

  • Tailwind CSS:CSS Utility Framework。
  • shadcn/ui: Provides the React UI component source code that can be copied into the project.
  • Radix UI: Commonly used to provide basic interaction and accessibility capabilities for Dialog, Popover and other components.

For example, Button, Dialog, Dropdown Menu and other components, shadcn/ui can provide a more mature component implementation based on Tailwind.

However, for a simple personal website, it is not necessary to introduce a complete UI component solution; basic Tailwind + a small number of reusable React components can meet many needs.

18. Frequently Asked Questions and Practical Suggestions

Class too long

For example:

<button className="inline-flex h-10 items-center justify-center rounded-md bg-blue-600 px-4 text-sm font-medium text-white shadow-sm transition-colors hover:bg-blue-700 focus-visible:outline-2 disabled:opacity-50">

This is one of the typical shortcomings of Tailwind.

Processing method:

  • Extract the repeating pattern as React Component.
  • Use clsx to manage conditional styles.
  • Use tailwind-merge to handle Class conflicts.
  • Define Theme Tokens for recurring design values.

Don’t rely too much on @apply

If all are packaged as custom CSS:

.button {
}
.card {
}
.container {
}
.header {
}

It is easy to fall back to the traditional CSS maintenance method.

For React projects, it is often more natural to use the Component reuse in preference.

Do not regard Tailwind as a complete component library

Tailwind is only responsible for the style and does not automatically provide:

  • Focus management for Dialog.
  • Keyboard interaction for Dropdown.
  • Form Validation。
  • Complete Accessibility behavior.

These still need to be implemented via React, native HTML or UI Component Library.

Note CSS and browser compatibility

Tailwind v4 takes advantage of modern CSS features and has limited support for older browsers. When compatibility with older browsers is required, the browser requirements for v4 should be checked first.


Summary

Knowledge pointsimportance
Utility-First CSScore
Spacing / Width / Heightcore
Flexbox / Gridcore
Responsive Designcore
Typography / Colorshigh frequency
Hover / Focus / Disabled Variantscore
Group / Peerimportant
Dark Modeimportant
@theme / Design Tokenscore
Arbitrary ValuesCommonly used
@apply / @utilityon demand
React Component Extractioncore
clsx / tailwind-mergeimportant
Class Detectionimportant
Container Querieson demand

Tailwind The five most important concepts:

  1. Utility-First: Use small-grained Class to combine styles directly instead of writing separate CSS for each element.
  2. Responsive Variants: Use prefixes such as sm:, md:, lg: to implement Mobile-First responsive design.
  3. State Variants: Use mechanisms such as hover:, focus:, group-hover: to express interaction status.
  4. Theme Tokens: Establish unified color, font, spacing and design specifications through @theme.
  5. Component Reuse: Reuse styles through components in React, manage condition Class through clsx and tailwind-merge.

Reference documentation

Back to top