English

Poradnik · Tailwind CSS · React

Tailwind CSS v4 w React i Vite – tokeny w @theme, warianty z cva, tryb ciemny i dostępność

Konfigurujemy Tailwind CSS v4 w aplikacji React + Vite i budujemy mały zestaw komponentów pierogarni – tokeny projektowe w @theme, tokeny semantyczne dla trybu ciemnego, przyciski z wariantami (cva + tailwind-merge), dostępne pola formularza i natywny dialog. Na koniec – kiedy Tailwind, a kiedy MUI.

Autor · · 18 min czytania

Tailwind CSS v4 to przepisany od zera silnik: konfiguracja przeniosła się z tailwind.config.js do CSS-a, tokeny projektowe stały się zwykłymi zmiennymi CSS, a integracja z Vite to jedna wtyczka. W tym poradniku zbudujesz stronę menu pierogarni z małym, ale porządnym zestawem komponentów – z wariantami, trybem ciemnym i dostępnością od pierwszej linijki.

Wymagania wstępne: podstawy CSS (flexbox, grid, zmienne CSS), React z hookami i TypeScript (zob. poradnik React). Znajomość Tailwind v3 nie jest potrzebna – różnice opisujemy po drodze.

1
wtyczka Vite – bez `tailwind.config.js` i bez PostCSS
22 kB
CSS całej strony – tylko klasy faktycznie użyte w kodzie
oklch
przestrzeń kolorów – domyślna paleta v4
0
bibliotek do modala – natywny `<dialog>`

Krok 1. Instalacja w Vite

npm create vite@latest pierogi-tailwind -- --template react-ts
cd pierogi-tailwind
npm install tailwindcss @tailwindcss/vite
npm install class-variance-authority clsx tailwind-merge @fontsource-variable/inter

Konfiguracja projektu

package.json
{
  "name": "pierogi-tailwind",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@fontsource-variable/inter": "^5.3.0",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "tailwind-merge": "^3.7.1"
  },
  "devDependencies": {
    "@tailwindcss/vite": "^4.3.5",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "tailwindcss": "^4.3.5",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// Tailwind v4: one Vite plugin, no tailwind.config.js and no PostCSS config.
export default defineConfig({
  plugins: [react(), tailwindcss()],
});

Tailwind v4 sam wykrywa pliki źródłowe (z pominięciem tego, co jest w .gitignore), więc nie podajesz już listy content. Jeśli używasz klas z pakietu w node_modules (np. własnej biblioteki komponentów), dopisz w CSS @source "../node_modules/moja-biblioteka";.

Krok 2. Tokeny projektowe w @theme

Cała konfiguracja motywu jest w pliku CSS. Ma dwie warstwy:

  1. Tokeny marki w @theme – skala koloru brand, font, promień karty, cień, animacja. Każda zmienna z przestrzeni nazw (--color-*, --font-*, --radius-*, --shadow-*, --animate-*) tworzy odpowiednie klasy.
  2. Tokeny semantyczne w @theme inline – canvas, surface, border, fg, muted, accent. Wskazują na zmienne (--surface), które blok .dark podmienia na ciemne odpowiedniki.

Tokeny, tryb ciemny i własne narzędzie

src/index.css
@import "tailwindcss";

/* Dark mode driven by a .dark class on <html> instead of only prefers-color-scheme. */
@custom-variant dark (&:where(.dark, .dark *));

/* 1. Brand tokens – every variable here becomes utilities: bg-brand-600, font-sans, rounded-card… */
@theme {
  --font-sans: "Inter Variable", ui-sans-serif, system-ui, sans-serif;

  --color-brand-50: oklch(0.97 0.02 350);
  --color-brand-100: oklch(0.93 0.05 350);
  --color-brand-300: oklch(0.8 0.12 352);
  --color-brand-500: oklch(0.64 0.2 355);
  --color-brand-600: oklch(0.56 0.2 357);
  --color-brand-700: oklch(0.49 0.18 358);
  --color-brand-900: oklch(0.36 0.12 358);

  --radius-card: 0.875rem;
  --shadow-card: 0 1px 2px oklch(0 0 0 / 0.06), 0 4px 16px oklch(0 0 0 / 0.06);
  --animate-pop: pop 160ms ease-out;

  @keyframes pop {
    from { transform: scale(0.96); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
  }
}

/* 2. Semantic tokens – components use bg-surface / text-muted, never raw greys.
   `inline` makes utilities reference the runtime variable, so .dark can swap it. */
@theme inline {
  --color-canvas: var(--canvas);
  --color-surface: var(--surface);
  --color-border: var(--border);
  --color-fg: var(--fg);
  --color-muted: var(--muted);
  --color-accent: var(--accent);
  --color-accent-fg: var(--accent-fg);
  --color-danger: var(--danger);
}

:root {
  --canvas: oklch(0.985 0.003 350);
  --surface: oklch(1 0 0);
  --border: oklch(0.92 0.005 350);
  --fg: oklch(0.22 0.01 350);
  --muted: oklch(0.5 0.01 350);
  --accent: var(--color-brand-600);
  --accent-fg: oklch(1 0 0);
  --danger: oklch(0.55 0.2 27);
}

.dark {
  --canvas: oklch(0.17 0.01 350);
  --surface: oklch(0.21 0.012 350);
  --border: oklch(0.3 0.012 350);
  --fg: oklch(0.95 0.005 350);
  --muted: oklch(0.7 0.01 350);
  --accent: var(--color-brand-300);
  --accent-fg: oklch(0.2 0.02 350);
  --danger: oklch(0.7 0.17 25);
}

@layer base {
  html { color-scheme: light; }
  html.dark { color-scheme: dark; }
  body { @apply bg-canvas font-sans text-fg antialiased; }
}

/* A custom utility that works with variants: hover:focus-ring, md:focus-ring… */
@utility focus-ring {
  @apply outline-2 outline-offset-2 outline-accent;
}
Diagram: Dwie warstwy tokenów: komponent zna tylko nazwy semantyczne

Dlaczego inline? Zwykły @theme generuje klasę bg-surface { background: var(--color-surface) }, a zmienna --color-surface jest wyliczana raz, na :root. Wersja inline wpisuje do klasy bezpośrednio var(--surface), więc wartość zmienia się razem z klasą .dark. Kolory zapisujemy w oklch – jasność (L) zmienia się w niej liniowo dla oka, więc skale i warianty ciemne łatwiej dobrać niż w HEX czy HSL.

@utility focus-ring to własna klasa narzędziowa. W odróżnieniu od zwykłej reguły CSS działa z wariantami: focus-visible:focus-ring, md:focus-ring.

Krok 3. Komponenty z wariantami: cva + tailwind-merge

Przycisk ma kilka wymiarów: intencję (główny, drugorzędny, duch, niebezpieczny), rozmiar i stany. Ciąg warunków w JSX szybko staje się nieczytelny. class-variance-authority (cva) zamienia to w tabelę: klasy bazowe, warianty, kombinacje i wartości domyślne, a VariantProps daje typy propsów za darmo.

Helper cn() i przycisk

src/lib/cn.ts
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

// clsx joins conditional classes, twMerge resolves conflicts: cn("px-4", "px-2") === "px-2".
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
src/components/ui/Button.tsx
import { cva, type VariantProps } from "class-variance-authority";
import type { ComponentProps } from "react";
import { cn } from "../../lib/cn.ts";

// All visual decisions in one table: base classes + variants + defaults.
export const buttonVariants = cva(
  [
    "inline-flex items-center justify-center gap-2 rounded-lg font-semibold whitespace-nowrap",
    "transition-colors duration-150 select-none",
    "focus-visible:focus-ring disabled:pointer-events-none disabled:opacity-50",
  ],
  {
    variants: {
      intent: {
        primary: "bg-accent text-accent-fg hover:bg-accent/90",
        secondary: "border border-border bg-surface text-fg hover:bg-canvas",
        ghost: "text-fg hover:bg-fg/5",
        danger: "bg-danger text-white hover:bg-danger/90",
      },
      size: {
        sm: "h-8 px-3 text-sm",
        md: "h-10 px-4 text-sm",
        lg: "h-12 px-6 text-base",
        icon: "size-10",
      },
    },
    compoundVariants: [{ intent: "ghost", size: "sm", class: "px-2" }],
    defaultVariants: { intent: "primary", size: "md" },
  },
);

type ButtonProps = ComponentProps<"button"> & VariantProps<typeof buttonVariants> & { loading?: boolean };

// React 19: `ref` arrives as a regular prop inside ...props – no forwardRef.
export function Button({ className, intent, size, loading = false, disabled, children, ...props }: ButtonProps) {
  return (
    <button
      type="button"
      className={cn(buttonVariants({ intent, size }), className)}
      disabled={disabled || loading}
      aria-busy={loading || undefined}
      {...props}
    >
      {loading && (
        <span className="size-4 animate-spin rounded-full border-2 border-current border-t-transparent" aria-hidden />
      )}
      {children}
    </button>
  );
}

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok 4. Karty, odznaki i dostępne pola
  • Krok 5. Tryb ciemny bez mignięcia
  • Krok 6. Dostępność: natywny dialog i warianty stanu
  • Krok 7. Składamy stronę
  • Tailwind czy MUI?
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się