Tailwind CSS: Tailwind CSS 暗黑模式与主题配置:dark前缀与@theme指令

1. 暗黑模式(dark:)

Tailwind 使用 dark: 前缀为暗黑模式定义样式,支持 mediaclass 两种策略。

▶ 示例

HTML 📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>暗黑模式演示</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class'
    }
  </script>
</head>
<body class="min-h-screen bg-white dark:bg-gray-900 transition-colors">
  <div class="max-w-4xl mx-auto p-8 space-y-8">
    <!-- 暗黑模式切换按钮 -->
    <div class="flex justify-end">
      <button onclick="document.documentElement.classList.toggle('dark')"
              class="p-2 rounded-lg bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200">
        切换暗黑模式
      </button>
    </div>

    <!-- 文字颜色 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
      <h3 class="text-gray-900 dark:text-white font-semibold text-lg mb-4">文字颜色</h3>
      <p class="text-gray-600 dark:text-gray-300">
        这段文字在亮色模式下为深灰色,暗黑模式下为浅灰色。
      </p>
      <p class="text-blue-600 dark:text-blue-400 mt-2">
        链接颜色也会根据模式变化。
      </p>
    </div>

    <!-- 卡片组件 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg dark:shadow-gray-700/50 p-6">
        <div class="w-12 h-12 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center mb-4">
          <span class="text-blue-600 dark:text-blue-400 text-xl">🎨</span>
        </div>
        <h4 class="text-gray-900 dark:text-white font-semibold mb-2">主题适配</h4>
        <p class="text-gray-600 dark:text-gray-400">卡片背景、阴影、文字颜色都适配暗黑模式。</p>
      </div>
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg dark:shadow-gray-700/50 p-6">
        <div class="w-12 h-12 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center mb-4">
          <span class="text-green-600 dark:text-green-400 text-xl">✨</span>
        </div>
        <h4 class="text-gray-900 dark:text-white font-semibold mb-2">平滑过渡</h4>
        <p class="text-gray-600 dark:text-gray-400">配合 transition-colors 实现平滑的颜色切换。</p>
      </div>
    </div>

    <!-- 表单元素 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
      <h3 class="text-gray-900 dark:text-white font-semibold mb-4">表单元素</h3>
      <div class="space-y-4">
        <input type="text" placeholder="输入框"
               class="w-full p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400">
        <button class="w-full p-3 bg-blue-600 dark:bg-blue-500 text-white rounded-lg hover:bg-blue-700 dark:hover:bg-blue-600 transition-colors">
          提交按钮
        </button>
      </div>
    </div>
  </div>
</body>
</html>
逻辑代码 59 行(超过 40 行限制,仅展示)

传统 CSS vs Tailwind 传统方式需要编写 @media (prefers-color-scheme: dark) 或手动添加 .dark 类并编写大量 CSS 规则,而 Tailwind 使用 dark:bg-gray-900 dark:text-white 等前缀直接声明。

💡 提示: darkMode: 'class' 策略需要在 <html> 元素上切换 dark 类。darkMode: 'media' 策略自动跟随系统偏好。


2. 自定义主题(tailwind.config)

通过 tailwind.config 文件可以扩展或覆盖默认主题,添加自定义颜色、字体、间距等。

▶ 示例

HTML 📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义主题演示</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: {
              50: '#eff6ff',
              100: '#dbeafe',
              200: '#bfdbfe',
              300: '#93c5fd',
              400: '#60a5fa',
              500: '#3b82f6',
              600: '#2563eb',
              700: '#1d4ed8',
              800: '#1e40af',
              900: '#1e3a8a',
            },
            accent: '#f59e0b',
            brand: '#8b5cf6',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
            display: ['Poppins', 'sans-serif'],
          },
          spacing: {
            '128': '32rem',
            '144': '36rem',
          },
          borderRadius: {
            '4xl': '2rem',
          },
        },
      },
    }
  </script>
</head>
<body class="min-h-screen bg-gray-100 p-8">
  <div class="max-w-4xl mx-auto space-y-8">
    <!-- 自定义颜色 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">自定义颜色</h3>
      <div class="flex flex-wrap gap-4">
        <div class="w-20 h-20 bg-primary-500 rounded-lg flex items-center justify-center text-white text-xs">primary-500</div>
        <div class="w-20 h-20 bg-primary-600 rounded-lg flex items-center justify-center text-white text-xs">primary-600</div>
        <div class="w-20 h-20 bg-primary-700 rounded-lg flex items-center justify-center text-white text-xs">primary-700</div>
        <div class="w-20 h-20 bg-accent rounded-lg flex items-center justify-center text-white text-xs">accent</div>
        <div class="w-20 h-20 bg-brand rounded-lg flex items-center justify-center text-white text-xs">brand</div>
      </div>
    </div>

    <!-- 自定义字体 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">自定义字体</h3>
      <p class="font-sans text-lg mb-2">font-sans:使用 Inter 字体</p>
      <p class="font-display text-lg">font-display:使用 Poppins 字体</p>
    </div>

    <!-- 自定义间距 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">自定义间距</h3>
      <div class="space-y-2">
        <div class="h-4 bg-primary-200 rounded" style="width: 32rem;">
          <span class="text-xs">w-128 (32rem)</span>
        </div>
        <div class="h-4 bg-primary-300 rounded" style="width: 36rem;">
          <span class="text-xs">w-144 (36rem)</span>
        </div>
      </div>
    </div>

    <!-- 自定义圆角 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">自定义圆角</h3>
      <div class="flex gap-4">
        <div class="w-24 h-24 bg-brand rounded-4xl flex items-center justify-center text-white text-xs">rounded-4xl</div>
        <div class="w-24 h-24 bg-accent rounded-full flex items-center justify-center text-white text-xs">rounded-full</div>
      </div>
    </div>
  </div>
</body>
</html>
逻辑代码 81 行(超过 40 行限制,仅展示)

传统 CSS vs Tailwind 传统方式需要在 CSS 中定义大量变量和类,而 Tailwind 通过 tailwind.configextend 选项扩展主题,自动生成对应的工具类。


3. @theme 指令(v4 新特性)

Tailwind v4 引入 @theme 指令,使用 CSS 原生语法定义主题变量,无需 JavaScript 配置文件。

▶ 示例

HTML 📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@theme 指令演示</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style type="text/tailwindcss">
    @theme {
      --color-primary-50: #eff6ff;
      --color-primary-100: #dbeafe;
      --color-primary-200: #bfdbfe;
      --color-primary-300: #93c5fd;
      --color-primary-400: #60a5fa;
      --color-primary-500: #3b82f6;
      --color-primary-600: #2563eb;
      --color-primary-700: #1d4ed8;
      --color-primary-800: #1e40af;
      --color-primary-900: #1e3a8a;

      --color-accent: #f59e0b;
      --color-brand: #8b5cf6;

      --font-sans: 'Inter', system-ui, sans-serif;
      --font-display: 'Poppins', sans-serif;

      --spacing-128: 32rem;
      --spacing-144: 36rem;

      --radius-4xl: 2rem;
    }
  </style>
</head>
<body class="min-h-screen bg-gray-100 p-8">
  <div class="max-w-4xl mx-auto space-y-8">
    <!-- @theme 定义的颜色 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">@theme 定义的颜色</h3>
      <div class="flex flex-wrap gap-4">
        <div class="w-20 h-20 bg-primary-500 rounded-lg flex items-center justify-center text-white text-xs">primary-500</div>
        <div class="w-20 h-20 bg-primary-600 rounded-lg flex items-center justify-center text-white text-xs">primary-600</div>
        <div class="w-20 h-20 bg-accent rounded-lg flex items-center justify-center text-white text-xs">accent</div>
        <div class="w-20 h-20 bg-brand rounded-lg flex items-center justify-center text-white text-xs">brand</div>
      </div>
    </div>

    <!-- @theme 定义的字体 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">@theme 定义的字体</h3>
      <p class="font-sans text-lg mb-2">font-sans:使用 Inter 字体</p>
      <p class="font-display text-lg">font-display:使用 Poppins 字体</p>
    </div>

    <!-- @theme 定义的间距 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">@theme 定义的间距</h3>
      <div class="space-y-2">
        <div class="h-4 bg-primary-200 rounded w-128">
          <span class="text-xs">w-128 (32rem)</span>
        </div>
        <div class="h-4 bg-primary-300 rounded w-144">
          <span class="text-xs">w-144 (36rem)</span>
        </div>
      </div>
    </div>

    <!-- @theme 定义的圆角 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">@theme 定义的圆角</h3>
      <div class="flex gap-4">
        <div class="w-24 h-24 bg-brand rounded-4xl flex items-center justify-center text-white text-xs">rounded-4xl</div>
      </div>
    </div>
  </div>
</body>
</html>
逻辑代码 48 行(超过 40 行限制,仅展示)

传统 CSS vs Tailwind 传统方式需要在 tailwind.config.js 中使用 JavaScript 对象定义主题,而 Tailwind v4 的 @theme 指令使用 CSS 原生变量语法,更直观且与 CSS 原生变量兼容。

💡 提示: @theme 指令中的变量名遵循 --color-*--font-*--spacing-*--radius-* 等命名约定,Tailwind 会自动生成对应的工具类。


4. CSS 原生变量与 Tailwind 集成

Tailwind v4 支持直接使用 CSS 原生变量,无需通过配置文件中转。

▶ 示例

HTML 📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS 原生变量集成</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    :root {
      --main-bg: #f8fafc;
      --card-bg: #ffffff;
      --text-primary: #1e293b;
      --text-secondary: #64748b;
      --border-color: #e2e8f0;
      --spacing-section: 2rem;
    }

    .dark {
      --main-bg: #0f172a;
      --card-bg: #1e293b;
      --text-primary: #f1f5f9;
      --text-secondary: #94a3b8;
      --border-color: #334155;
    }
  </style>
</head>
<body class="min-h-screen p-8" style="background-color: var(--main-bg);">
  <div class="max-w-4xl mx-auto space-y-8" style="gap: var(--spacing-section);">
    <!-- 暗黑模式切换 -->
    <div class="flex justify-end">
      <button onclick="document.documentElement.classList.toggle('dark')"
              class="p-2 rounded-lg" style="background-color: var(--card-bg); color: var(--text-primary);">
        切换暗黑模式
      </button>
    </div>

    <!-- 使用 CSS 变量的卡片 -->
    <div class="rounded-lg shadow p-6" style="background-color: var(--card-bg); border: 1px solid var(--border-color);">
      <h3 class="font-semibold text-lg mb-4" style="color: var(--text-primary);">CSS 原生变量</h3>
      <p style="color: var(--text-secondary);">
        这个卡片使用 CSS 原生变量定义颜色,通过 style 属性应用。
      </p>
    </div>

    <!-- 混合使用 -->
    <div class="rounded-lg shadow p-6 bg-white dark:bg-gray-800">
      <h3 class="font-semibold text-lg mb-4 text-gray-900 dark:text-white">混合使用</h3>
      <p class="text-gray-600 dark:text-gray-300 mb-4">
        可以同时使用 Tailwind 类和 CSS 变量。
      </p>
      <div class="flex gap-4">
        <div class="w-16 h-16 rounded-lg" style="background-color: var(--text-primary);"></div>
        <div class="w-16 h-16 rounded-lg bg-blue-500"></div>
        <div class="w-16 h-16 rounded-lg" style="background-color: var(--border-color);"></div>
      </div>
    </div>
  </div>
</body>
</html>
逻辑代码 42 行(超过 40 行限制,仅展示)
💡 提示: CSS 原生变量适合需要在运行时动态修改的值(如主题切换),Tailwind 类适合静态样式。


5. 插件系统初探

Tailwind 插件可以扩展框架功能,添加自定义工具类、变体或基础样式。

▶ 示例

HTML 📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>插件系统演示</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    const plugin = tailwind.plugin;

    // 自定义插件:添加文本渐变工具类
    const textGradientPlugin = plugin(function({ addUtilities }) {
      addUtilities({
        '.text-gradient-blue': {
          'background': 'linear-gradient(to right, #3b82f6, #8b5cf6)',
          '-webkit-background-clip': 'text',
          '-webkit-text-fill-color': 'transparent',
          'background-clip': 'text',
        },
        '.text-gradient-red': {
          'background': 'linear-gradient(to right, #ef4444, #f97316)',
          '-webkit-background-clip': 'text',
          '-webkit-text-fill-color': 'transparent',
          'background-clip': 'text',
        },
      });
    });

    tailwind.config = {
      plugins: [textGradientPlugin],
    }
  </script>
</head>
<body class="min-h-screen bg-gray-100 p-8">
  <div class="max-w-4xl mx-auto space-y-8">
    <!-- 插件添加的工具类 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">自定义插件:文本渐变</h3>
      <p class="text-4xl font-bold text-gradient-blue mb-4">蓝色渐变文字</p>
      <p class="text-4xl font-bold text-gradient-red">红色渐变文字</p>
    </div>

    <!-- 常用第三方插件示例说明 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="font-semibold mb-4">常用插件</h3>
      <div class="space-y-4">
        <div class="p-4 bg-gray-50 rounded-lg">
          <h4 class="font-medium text-gray-900">@tailwindcss/typography</h4>
          <p class="text-gray-600 text-sm">为长文本内容提供优美的排版样式,使用 prose 类。</p>
        </div>
        <div class="p-4 bg-gray-50 rounded-lg">
          <h4 class="font-medium text-gray-900">@tailwindcss/forms</h4>
          <p class="text-gray-600 text-sm">为表单元素提供基础样式重置,使表单在不同浏览器中表现一致。</p>
        </div>
        <div class="p-4 bg-gray-50 rounded-lg">
          <h4 class="font-medium text-gray-900">@tailwindcss/aspect-ratio</h4>
          <p class="text-gray-600 text-sm">提供 aspect-ratio 工具类,用于控制元素的宽高比。</p>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
逻辑代码 57 行(超过 40 行限制,仅展示)

传统 CSS vs Tailwind 传统方式需要手动编写 CSS 类并引入,而 Tailwind 插件通过 addUtilitiesaddComponentsaddBase 等 API 自动集成到构建流程中。

⚠️ 注意: Tailwind v4 中插件 API 有所变化,推荐使用 CSS 原生方式扩展功能。@theme 指令和 @layer 基本可以替代大部分插件场景。

❓ 常见问题

Q darkMode: 'class' 和 darkMode: 'media' 有什么区别?
A 'media' 策略自动跟随系统的 prefers-color-scheme 媒体查询,用户无法手动切换。'class' 策略需要在 <html> 元素上手动切换 dark 类,适合提供切换按钮的场景。
Q @theme 指令和 tailwind.config 有什么区别?
A tailwind.config 使用 JavaScript 对象定义主题,需要配置文件。@theme 指令使用 CSS 原生变量语法,直接在 CSS 中定义,是 Tailwind v4 的新特性,更推荐使用。
Q 如何在暗黑模式下使用不同的图片?
A 使用 dark: 前缀配合 hiddenblock。例如 <img class="block dark:hidden" src="light.png"><img class="hidden dark:block" src="dark.png">
Q CSS 变量和 Tailwind 类如何选择?
A 静态样式优先使用 Tailwind 类,需要运行时动态修改的值使用 CSS 变量。两者可以混合使用,如 style="color: var(--text-primary)"

📖 小节

📝 作业

  1. ⭐ 创建一个支持暗黑模式的登录页面,包含输入框、按钮和卡片,使用 dark: 前缀适配所有元素

  2. ⭐⭐ 使用 @theme 指令自定义一个品牌主题(包含主色调、辅助色、字体),并创建一个展示页面

  3. ⭐⭐⭐ 创建一个主题切换器,支持亮色/暗黑/系统三种模式,使用 CSS 变量实现主题颜色动态切换

Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏