You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS中引用TailwindCSS颜色(如bg-gray-100)?

能否在CSS中引用TailwindCSS的颜色代码?

不能直接将bg-gray-100这类Tailwind工具类名作为CSS变量的值,因为它不是CSS能识别的合法颜色值,这样写无法生效。要实现类似需求,可以用以下两种方法:

方法一:使用Tailwind的theme()函数引用颜色值

通过Tailwind内置的theme()函数,直接调用主题配置里的颜色值来定义CSS变量,编译后变量会被替换为对应颜色的实际值:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: theme('colors.gray.100');
  }
}

这样--background最终会被编译成bg-gray-100对应的颜色(比如默认的#f3f4f6或你自定义的HSL值),后续可以在样式中通过var(--background)使用这个颜色。

方法二:通过Tailwind配置关联变量与颜色

先在tailwind.config.js中扩展颜色系统,将自定义变量与目标颜色绑定:

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      colors: {
        background: 'var(--background)',
      },
    },
  },
}

然后在CSS中定义变量时,依然用theme()函数或直接写颜色值:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: theme('colors.gray.100');
  }
}

之后你就可以像使用Tailwind原生类一样,用bg-background来应用这个颜色,效果和bg-gray-100完全一致。

内容的提问来源于stack exchange,提问作者user3357926

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:16:09