Css

Dark Mode

使用 CSS 变量实现 Tailwind 换肤效果

核心原理

借助 CSS 变量定义颜色值,在 Tailwind 配置里引用这些变量,通过修改根元素上的 CSS 变量值来实现主题切换。

具体步骤

  1. 定义 CSS 变量
    • 在 CSS 文件中,为不同主题定义对应的 CSS 变量。默认主题在 :root 中定义,其他主题通过自定义属性(如 [data - theme="dark"])定义,示例如下:
/* 默认主题 */
:root {
  --primary-color: #007bff;
  --secondary-color: #6c757d;
}

/* 黑暗主题 */
[data-theme="dark"] {
  --primary-color: #212529;
  --secondary-color: #adb5bd;
}
  1. Tailwind 配置
    • 打开 tailwind.config.js 文件,在 theme.extend.colors 中使用 CSS 变量定义颜色,示例如下:
module.exports = {
  darkMode: "class", //默认情况下,Tailwind 未开启深色模式变体,需要手动开启。
  theme: {
    extend: {
      colors: {
        primary: "var(--primary-color)",
        secondary: "var(--secondary-color)"
      }
    }
  }
};
  1. 使用 Tailwind 类
    • 在 HTML 文件里引入 CSS 文件,并使用定义好的 Tailwind 颜色类,同时添加一个用于切换主题的按钮,示例如下:
<template>
  <el-button type="primary" @click="toggleDark()">换色</el-button>

  <!-- tailwind -->
  <div class="bg-primary">tailwind1</div>
  <div class="bg-secondary">tailwind2</div>
</template>

<script lang="ts" setup>
import { useDark, useToggle } from "@vueuse/core";

const isDark = useDark();
const toggleDark = useToggle(isDark);
</script>

优势

这种方法灵活性高,能够在运行时动态切换主题,且代码结构清晰,便于维护和扩展新的主题。