电脑显示器上显示的HTML和CSS代码,突显Web开发和编程。

2026年Tailwind CSS v4:附实践示例的完整指南

📷 Bibek ghosh / Pexels

2026年Tailwind CSS v4:附实践示例的完整指南

通过这份完整指南掌握Tailwind CSS v4。学习全新的CSS优先配置、Oxide引擎、新工具类、深色模式以及从v3的迁移方法。

2026年3月19日6分钟阅读

Tailwind CSS v4代表了该框架自诞生以来最大的革新。在2025年初发布,到2026年已完全成熟的v4引入了CSS优先配置系统、名为Oxide的全新重写引擎、显著的性能提升以及现代化的工具类集合。如果你一直在使用Tailwind v3,升级到v4将改变你对配置和主题的思维方式。本指南将带你了解所有需要知道的内容。

Tailwind CSS v4的变化

Tailwind v4不仅仅是一个增量更新。它是对框架底层工作方式的根本性重新思考。以下是主要变化:

  • CSS优先配置:不再需要tailwind.config.js。主题值、自定义工具类和变体都使用@theme和其他指令直接在CSS中定义。
  • Oxide引擎:用Rust编写的新高性能引擎,处理解析、编译和类检测的速度比v3快数个数量级。
  • 现代CSS特性:内置支持@layer、级联层、color-mix()oklch()、容器查询和用于动画的@starting-style
  • 简化安装:只需一个包,零配置即可开始。
  • 新的默认主题:使用OKLCH的扩展色板、更新的间距比例和改进的排版默认值。

开始使用Tailwind CSS v4

安装

设置Tailwind v4比以往更简单。不需要单独的PostCSS插件或配置文件。

# Install Tailwind CSS v4
npm install tailwindcss @tailwindcss/vite

# Or with the CLI
npm install tailwindcss @tailwindcss/cli

对于基于Vite的项目,将插件添加到Vite配置中:

// vite.config.ts
import { defineConfig } from 'vite';
import tailwindcss from '@tailwindcss/vite';

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

然后在主CSS文件中导入Tailwind:

/* app.css */
@import "tailwindcss";

这就是全部设置。不需要tailwind.config.js,不需要postcss.config.js,不需要配置内容路径。Oxide引擎会自动检测你的源文件并扫描类名。

使用CLI

如果你不使用Vite,CLI同样好用:

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

使用@theme进行CSS优先配置

v4中最大的概念转变是所有自定义都在CSS中进行,而不是JavaScript。@theme指令取代了旧的tailwind.config.js主题对象。

定义自定义颜色

@import "tailwindcss";

@theme {
  --color-brand: #4f46e5;
  --color-brand-light: #818cf8;
  --color-brand-dark: #3730a3;
  --color-surface: #f8fafc;
  --color-surface-dark: #1e293b;
}

这些CSS变量自动成为可用的Tailwind工具类:

<div class="bg-brand text-white">
  <h1 class="text-brand-light">Hello, Tailwind v4</h1>
</div>

自定义间距和尺寸

@theme {
  --spacing-18: 4.5rem;
  --spacing-128: 32rem;
  --width-content: 72rem;
  --width-sidebar: 20rem;
}

自定义字体

@theme {
  --font-sans: "Inter", "system-ui", sans-serif;
  --font-mono: "JetBrains Mono", "Fira Code", monospace;
  --font-display: "Cal Sans", "Inter", sans-serif;
}

覆盖与扩展默认主题

默认情况下,@theme扩展内置主题。如果你想完全替换一个命名空间,使用--*通配符重置:

@theme {
  /* Remove all default colors, only use these */
  --color-*: initial;
  --color-white: #ffffff;
  --color-black: #000000;
  --color-primary: #2563eb;
  --color-secondary: #7c3aed;
  --color-gray-50: #f9fafb;
  --color-gray-100: #f3f4f6;
  --color-gray-900: #111827;
}

Oxide引擎

底层上,Tailwind v4使用了名为Oxide的新引擎,用Rust编写并编译为原生代码。性能差异非常显著。

性能提升

Oxide引擎相比v3的JavaScript引擎实现了显著的速度提升:

  • 初始构建时间通常快3-10倍,具体取决于项目规模。
  • 增量重建在开发过程中几乎是即时的,通常在5毫秒以下。
  • 内存使用由于Rust在没有垃圾回收器的情况下管理内存而显著降低。

对于拥有数十万个类的大型monorepo项目,差异尤为明显。v3可能需要数秒进行完整重建,而v4只需数百毫秒即可完成。

自动内容检测

最好的用户体验改进之一是你不再需要指定内容路径。Oxide引擎自动检测和扫描你的项目文件。它使用启发式方法查找模板文件、JSX/TSX组件和其他类名来源。

如果你需要显式包含或排除文件,可以使用@source指令:

@import "tailwindcss";

/* Add additional source paths */
@source "../shared-components/**/*.tsx";

/* Exclude a path */
@source not "../node_modules";

新的和更新的工具类

Tailwind v4引入了几个新的工具类,并改进了现有的工具类以利用现代CSS特性。

容器查询

容器查询让你能够根据父容器的大小而不是视口来设置元素样式。Tailwind v4提供一流支持。

<div class="@container">
  <div class="flex flex-col @md:flex-row @lg:grid @lg:grid-cols-3 gap-4">
    <div class="p-4 bg-white rounded-lg">Card 1</div>
    <div class="p-4 bg-white rounded-lg">Card 2</div>
    <div class="p-4 bg-white rounded-lg">Card 3</div>
  </div>
</div>

@container类建立包含上下文,@md:@lg:前缀根据容器宽度应用样式。

现代颜色函数

Tailwind v4默认使用OKLCH颜色,提供感知均匀的色彩空间。你也可以使用color-mix()进行动态颜色操作:

@theme {
  --color-primary: oklch(0.6 0.25 265);
  --color-primary-hover: oklch(0.5 0.25 265);
}
<button class="bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded">
  Click me
</button>

3D变换

<div class="perspective-500">
  <div class="rotate-y-12 hover:rotate-y-0 transition-transform duration-300">
    <img src="/card.jpg" alt="3D card" class="rounded-xl shadow-lg" />
  </div>
</div>

新的渐变工具类

v4通过附加功能扩展了渐变支持:

<!-- Gradient with interpolation in OKLCH for smoother transitions -->
<div class="bg-linear-to-r from-blue-500 to-purple-500 bg-interpolate-oklch">
  Smooth gradient
</div>

<!-- Conic gradient -->
<div class="bg-conic from-red-500 via-yellow-500 to-green-500">
  Color wheel
</div>

not-变体

not-变体利用CSS :not()反转任何其他变体:

<div class="opacity-50 not-hover:opacity-100">
  Fades on hover instead of appearing
</div>

<input class="border-gray-300 not-focus:border-transparent" />

动画的Starting Style

starting变体让你能够为@starting-style规则定义样式,使DOM中出现的元素具有入场动画:

<dialog class="opacity-0 starting:opacity-0 open:opacity-100 transition-opacity">
  <p>This dialog fades in when opened</p>
</dialog>

v4中的响应式设计

响应式设计在概念上以相同方式工作,使用熟悉的断点前缀语法。不过v4内部使用了现代CSS特性。

默认断点

默认断点保持实用:

前缀最小宽度常见用途
sm640px大屏手机、横屏
md768px平板
lg1024px小型笔记本
xl1280px桌面
2xl1536px大屏幕

自定义断点

@theme {
  --breakpoint-xs: 475px;
  --breakpoint-3xl: 1920px;
}
<div class="grid grid-cols-1 xs:grid-cols-2 md:grid-cols-3 3xl:grid-cols-4">
  <!-- Responsive grid -->
</div>

响应式布局示例

<header class="flex flex-col sm:flex-row items-center justify-between p-4 lg:px-8">
  <a href="/" class="text-xl font-bold">Brand</a>
  <nav class="hidden md:flex gap-6 text-sm font-medium">
    <a href="/features" class="hover:text-brand">Features</a>
    <a href="/pricing" class="hover:text-brand">Pricing</a>
    <a href="/docs" class="hover:text-brand">Docs</a>
  </nav>
  <button class="md:hidden p-2" aria-label="Menu">
    <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
    </svg>
  </button>
</header>

深色模式

Tailwind v4继续通过dark:变体支持深色模式。默认使用prefers-color-scheme媒体查询,但你可以切换到基于类或基于选择器的切换。

基本深色模式

<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen">
  <h1 class="text-2xl font-bold">Welcome</h1>
  <p class="text-gray-600 dark:text-gray-400">This adapts to your system theme.</p>
</div>

基于类的深色模式

要使用JavaScript切换深色模式而不依赖系统设置:

@import "tailwindcss";

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

现在父元素有dark类时深色模式就会激活:

<html class="dark">
  <body class="bg-white dark:bg-gray-950">
    <!-- Dark mode active -->
  </body>
</html>
// Toggle dark mode with JavaScript
function toggleDarkMode() {
  document.documentElement.classList.toggle('dark');
}

构建主题感知组件

<div class="rounded-xl border border-gray-200 dark:border-gray-800
            bg-white dark:bg-gray-900
            shadow-sm dark:shadow-gray-950/50
            p-6">
  <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
    Settings
  </h3>
  <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
    Manage your account preferences.
  </p>
  <button class="mt-4 px-4 py-2 rounded-lg
                 bg-brand text-white
                 hover:bg-brand-dark
                 focus:outline-none focus:ring-2 focus:ring-brand/50">
    Save Changes
  </button>
</div>

动画工具类

Tailwind v4大幅扩展了动画支持,使创建精致的交互更加容易,无需自定义CSS。

过渡工具类

<!-- Smooth hover effect -->
<button class="bg-blue-600 hover:bg-blue-700
               transform hover:scale-105
               transition-all duration-200 ease-out
               text-white px-6 py-3 rounded-lg">
  Hover me
</button>

<!-- Transition specific properties -->
<div class="transition-colors duration-300 bg-gray-100 hover:bg-blue-100">
  Color transition only
</div>

内置动画

<!-- Spin animation for loading indicators -->
<svg class="animate-spin h-5 w-5 text-white" viewBox="0 0 24 24">
  <!-- spinner SVG -->
</svg>

<!-- Pulse animation -->
<div class="animate-pulse bg-gray-200 rounded h-4 w-3/4"></div>

<!-- Bounce -->
<div class="animate-bounce">Scroll down</div>

使用@theme自定义动画

@theme {
  --animate-slide-in: slide-in 0.3s ease-out;
  --animate-fade-up: fade-up 0.5s ease-out;
}

@keyframes slide-in {
  from { transform: translateX(-100%); }
  to { transform: translateX(0); }
}

@keyframes fade-up {
  from {
    opacity: 0;
    transform: translateY(1rem);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
<div class="animate-slide-in">Slides in from the left</div>
<div class="animate-fade-up">Fades up into view</div>

从Tailwind v3迁移到v4

从v3到v4的迁移需要一些工作量,但Tailwind团队提供了一个可以自动处理大多数更改的代码迁移工具。

运行升级工具

npx @tailwindcss/upgrade

此工具将扫描你的项目并自动将大多数v3模式转换为v4等价物。它处理工具类重命名、配置迁移和导入更新。

主要迁移变更

v3v4说明
tailwind.config.jsCSS中的@theme配置移至CSS
@tailwind base/components/utilities@import "tailwindcss"单一导入
bg-opacity-50bg-black/50不透明度修饰符语法
text-opacity-75text-white/75不透明度修饰符语法
decoration-clonebox-decoration-clone重命名
flex-shrink-0shrink-0简化(v3中已可用)
flex-growgrow简化
overflow-clipoverflow-clip相同
配置中的content路径自动检测无需配置
配置中的darkMode: 'class'CSS中的@variant dark (...)基于CSS

手动步骤

运行升级工具后,手动检查以下方面:

  1. 自定义插件:v3 JavaScript插件需要使用@utility@variant指令重写为CSS。
  2. 自定义主题值:从tailwind.config.js移到CSS中的@theme块。
  3. 第三方插件:检查它们是否已针对v4兼容性进行更新。

将v3插件转换为v4

v3插件(JavaScript):

// v3: tailwind.config.js plugin
const plugin = require('tailwindcss/plugin');

module.exports = {
  plugins: [
    plugin(function({ addUtilities }) {
      addUtilities({
        '.text-balance': {
          'text-wrap': 'balance',
        },
      });
    }),
  ],
};

v4等价物(CSS):

/* v4: defined directly in CSS */
@utility text-balance {
  text-wrap: balance;
}

转换v3自定义变体

v3(JavaScript):

// v3
plugin(function({ addVariant }) {
  addVariant('hocus', ['&:hover', '&:focus']);
});

v4(CSS):

/* v4 */
@variant hocus (&:hover, &:focus);

构建完整组件

让我们把所有内容结合起来,构建一个展示v4特性的定价卡组件:

<div class="@container max-w-sm mx-auto">
  <div class="rounded-2xl border border-gray-200 dark:border-gray-800
              bg-white dark:bg-gray-900
              shadow-xl shadow-gray-900/5 dark:shadow-gray-950/50
              p-8
              transition-all duration-300
              hover:shadow-2xl hover:-translate-y-1">

    <h3 class="text-sm font-semibold text-brand uppercase tracking-wider">
      Pro Plan
    </h3>

    <div class="mt-4 flex items-baseline gap-1">
      <span class="text-5xl font-bold text-gray-900 dark:text-white">$29</span>
      <span class="text-gray-500 dark:text-gray-400">/month</span>
    </div>

    <p class="mt-4 text-sm text-gray-600 dark:text-gray-400">
      Everything you need to build and ship faster.
    </p>

    <ul class="mt-8 space-y-3 text-sm">
      <li class="flex items-center gap-3 text-gray-700 dark:text-gray-300">
        <svg class="w-5 h-5 text-brand shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>
        Unlimited projects
      </li>
      <li class="flex items-center gap-3 text-gray-700 dark:text-gray-300">
        <svg class="w-5 h-5 text-brand shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>
        Priority support
      </li>
      <li class="flex items-center gap-3 text-gray-700 dark:text-gray-300">
        <svg class="w-5 h-5 text-brand shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
        </svg>
        Advanced analytics
      </li>
    </ul>

    <button class="mt-8 w-full rounded-lg bg-brand py-3 text-sm font-semibold text-white
                   hover:bg-brand-dark
                   focus:outline-none focus:ring-2 focus:ring-brand/50 focus:ring-offset-2
                   dark:focus:ring-offset-gray-900
                   transition-colors duration-200">
      Get started
    </button>
  </div>
</div>

总结

Tailwind CSS v4是该框架的重大飞跃。向CSS优先配置的转变使项目设置和理解更加简单。Oxide引擎消除了构建性能方面的顾虑。基于容器查询和OKLCH颜色等现代CSS特性的新工具类,让你在编写更少自定义CSS的同时拥有更强大的工具。

如果你正在开始一个新项目,没有理由不使用v4。如果你正在维护v3项目,升级工具使大多数代码库的迁移变得简单。社区和生态系统已完全接受了v4,开发者体验比以往任何时候都好。

使用我们的CSS到Tailwind转换器快速转换现有CSS。

开始试验新特性,特别是容器查询和@theme指令。它们从根本上改变了你处理组件设计的方式,一旦采用,回退将感觉像是降级。

相关文章