如何在Tailwind CSS中使用CSS变量

67

我能否在Tailwind CSS中使用CSS变量呢?例如,假设我有以下这些变量:

--primary-color: #fff;
--secondary-color: #000;

我想在Tailwind中这样使用它们:

<div class="bg-primary-color">
  <h1>Hello World</h1>
</div>

我应该如何实现这个目标?

7个回答

70

阿曼多的答案对我没有用,但是经过这个更改,它确实有效。

global.css:

不需要针对类或ID进行目标定位。您可以使用伪选择器直接针对根目录进行目标定位 https://www.w3schools.com/cssref/sel_root.asp

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

:root {
  --primary-color: #fff;
  --secondary-color: #000;
}

关于tailwind.config.js

module.exports = {
  theme: {
    extend: {
      colors: {
        "primary-color": "var(--primary-color)",
        "secondary-color": "var(--secondary-color)"
      },
    },
  },
};

1
我花了一分钟才意识到字符串中也有 var - bholben
2
如果你试图改变颜色的透明度,这样是行不通的。例如:bg-primary/50 - Renan Coelho

68
现在Tailwind从v3.0开始支持将CSS自定义属性作为任意值使用。具体请参见文档

:root {
  --text-color: red;
  --text-size: 5rem;
}
<script src="https://cdn.tailwindcss.com"></script>

<span class="text-[color:var(--text-color)] text-[length:var(--text-size)] font-bold">
  Hello world!
</span>


5
烦人的事情是每次都要定义数据类型,这也使它看起来非常臃肿,但至少它能工作。 - Thielicious
@Thielicious 您可以在根元素上使用媒体查询来支持媒体暗模式,这将实现相同的效果。如果您使用 .dark 方法,还可以在 :root 元素上使用类。 - qodeninja

24

假设您已经将 TailwindCSS 添加到您的项目中,并且您的 CSS 文件名为 global.css

首先,您需要编辑 global.css 文件,使其看起来像这样:

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

.root,
#root,
#docs-root {
  --primary-color: #fff;
  --secondary-color: #000;
}

然后,为了能够使用它们,您需要像这样在 tailwind.config.js 中更新新的CSS变量:

module.exports = {
  theme: {
    extend: {
      colors: {
        "primary-color": "var(--primary-color)",
        "secondary-color": "var(--secondary-color)"
      },
    },
  },
};

你现在可以根据需要使用这些变量:

<div class="bg-primary-color">
  <h1>Hello World</h1>
</div>

这是我首选的解决方案,但它有一个缺点:它不能自动集成Tailwind的暗模式支持。您必须在root规则周围添加媒体查询(或类,如果您正在使用基于类的暗模式)才能实现该功能。 - James A. Rosen
在我的情况下,我不得不为全局CSS添加:root选择器以用于变量。 - JanBrus

5
如果你希望你的变量能够与透明度修饰符语法一起使用,你需要按照以下方式定义它们:
:root {
  --color-primary: 255 115 179;
  --color-secondary: 111 114 185;
}

然后在您的配置文件中使用它们:
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    colors: {
      // Using modern `rgb`
      primary: 'rgb(var(--color-primary) / <alpha-value>)',
      secondary: 'rgb(var(--color-secondary) / <alpha-value>)',

      // Using modern `hsl`
      primary: 'hsl(var(--color-primary) / <alpha-value>)',
      secondary: 'hsl(var(--color-secondary) / <alpha-value>)',
    }
  }
}

基本上,在使用之前,您需要将十六进制颜色转换为RGB格式,否则它们将无法正常工作。这是文档的链接:https://tailwindcss.com/docs/customizing-colors#using-css-variables

4
你可以使用这个插件轻松配置它。(支持深色模式) https://github.com/mertasan/tailwindcss-variables
npm install -D @mertasan/tailwindcss-variables

用法:

// tailwind.config.js

module.exports = {
  theme: {
    colors: {
        red: {
            50: 'var(--colors-red-50)'
        }
    }
    variables: {
      DEFAULT: {
        sizes: {
          small: '1rem',
          button: {
            size: '2rem'
          }
        },
        colors: {
          red: {
            50: '#ff3232',
          },
        },
      },
      '.container': {
        sizes: {
          medium: '1.5rem',
        },
      },
    },
  },
  plugins: [
    require('@mertasan/tailwindcss-variables')
  ]
}

输出:

:root {
  --sizes-small: 1rem;
  --sizes-button-size: 2rem;
  --colors-red-50: #ff3232
}

.container {
  --sizes-medium: 1.5rem
}

1
我猜测在某个时候,Tailwind没有内置CSS变量。我正在使用tailwindcss@2.2.4版本,并且能够在没有插件的情况下引用CSS变量。 - bholben

2

You can use font family CSS variables with Tailwind CSS by following these steps:

Define your font family CSS variables in a global CSS file, such as global.css, and target the root element or a custom selector. For example:
:root {
  --font-sans: "Helvetica", "Arial", sans-serif;
  --font-serif: "Georgia", "Times New Roman", serif;
}
Update your tailwind.config.js file to include the font family CSS variables under the theme.fontFamily property. For example:
module.exports = {
  theme: {
    fontFamily: {
      sans: "var(--font-sans)",
      serif: "var(--font-serif)",
    },
  },
};
Use the font family CSS variables as desired in your HTML elements with Tailwind classes. For example:
<div className="font-sans">
  <h1>Hello World</h1>
</div>


0

或者,使用带有 JS 框架的 CSS 变量:

当我第一次使用 Tailwind 和 Svelte 工作时,我正在寻找解决方案,并发现可以使用 style 属性:

<script>
let cssVariables = {
  'primary-color': "#ffffff", 
  'secondary-color': "#000"
}

let styleValues = Object.entries(cssVariables)
.map(([key, value]) => `--${key}:${value}`)
.join(';')
</script>

<p style={styleValues} 
class="text-center text-[4vmax] text-[color:var(--primary-color)]">
  Hello World
</p>

上面的代码创建了一个对象,然后将该对象转换为字符串,该字符串的作用类似于纯CSS,每个属性都连接到该字符串中。 这在Svelte中可以工作,但是在HTML中无法使用。 如果您想在HTML中使用Tailwind,则必须编写整个字符串:
<p style="--primary-color:#ffffff;--secondary-color:#000"
class="text-[4vmax] text-center text-[color:var(--primary-color)]">
  Hello World
</p>

因此,我建议您使用一个帮助您使用数据绑定的框架。此外,还有其他一些可以使用此技巧完成的事情,例如响应式CSS(以下是Svelte方式):

<script>
$: changingHue = 0
setInterval(() => changing_hue++, 250)
$: cssVariables = {
  'primary-color': `hsl(${changingHue} 100% 70%)`, 
  'secondary-color': "#000"
}

$: styleValues = Object.entries(cssVariables)
.map(([key, value]) => `--${key}:${value}`)
.join(';')
</script>

<p style={styleValues} 
class="text-center text-[4vmax] text-[color:var(--primary-color)]">
  Hello World
</p>

总之,您不需要另一个库来使Tailwind使用CSS变量,只需使用JavaScript甚至HTML就足够了。

4
将CSS和JS混合使用应该是最后的选择,因为只用CSS也可以实现。 - petitkriket
@petitkriket 是的,在一个简单的项目中,CSS 和它的变量就足够了。 - user17968408

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接