tailwind v4 主题切换

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

@theme {
  --font-family-sans: "Inter", sans-serif;
}

@theme inline {
  --color-foreground: var(--foreground);
}

/* 定义不同类下的 css 变量,主题切换时只需切换根元素的类 */
:root {
  --foreground: oklch(0.145 0 0);
}

.dark {
  --foreground: oklch(0.985 0 0);
}

前缀类行为

使用 @custom-variant 指令定义前缀类行为,表示当前元素在 &:is(.dark *) 上下文内时触发

dark:text-red-500 即表示在 .dark 类下文本颜色为红色

主题指令 @theme

示例中的 --font-family-* 将会生成以下类:

.font-family-sans {
  font-family: var(--font-family-sans) /* "Inter", sans-serif */;
}

如果变量要使用 css 变量,则需要使用 @theme inline 指令参数

示例中的 --color-* 将会生成以下类:

.text-foreground {
  color: var(--foreground);
}
.border-foreground {
  border-color: var(--foreground);
}
/* ...等等有颜色属性的类都会生成 */

切换主题

document.documentElement.classList.toggle("dark", initial === "dark");