跳到正文
技术

Tailwind 4 的 @theme inline 与运行时换主题

📅 创建 ·☕ 约 1 分钟·✍ 238 字
T

Tailwind 4 不再用 tailwind.config.js

v4 把配置搬进了 CSS:

@import 'tailwindcss';

@theme {
  --color-brand: #7ec8e3;
  --radius-card: 18px;
}

这样 bg-brandrounded-card 就都能用了。

问题:主题切换时不生效

我一开始这么写:

@theme {
  --color-bg: #0d1b2a;
}
html[data-theme='light'] {
  --color-bg: #f5faff;
}

结果切到浅色,bg-bg 还是深蓝。

原因是 @theme 会在构建时把值内联进生成的工具类里:

.bg-bg { background-color: #0d1b2a; }  /* 值被写死了 */

解法:@theme inline

:root { --bg: #0d1b2a; }
html[data-theme='light'] { --bg: #f5faff; }

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

加了 inline 之后,生成的工具类变成:

.bg-bg { background-color: var(--bg); }

变量在运行时解析,data-theme 一改,全站跟着变。

过渡动画的坑

一开始我给所有元素加了过渡:

html.theme-switching * { transition: background-color 0.4s ease !important; }

切换瞬间掉帧掉得厉害 —— 通配选择器让浏览器对每一个元素做样式重算。

后来改成只挂二十来个容器,并且在切换的 400ms 里临时关掉 backdrop-filter

html.theme-switching .t-backdrop {
  backdrop-filter: none !important;
}

毛玻璃元素的重绘是切换卡顿的大头,关掉之后立刻就顺了。

小结

想要的效果 写法
固定色值 @theme { --color-x: #fff }
跟随主题 @theme inline { --color-x: var(--x) }
更多「技术」