怎样在TailwindCSS中为颜色创建别名?

huangapple go评论78阅读模式
英文:

How to create an alias for a color in TailwindCSS?

问题

我正在从我们的设计系统导入一堆颜色令牌我想给其中一种颜色取个别名以便我可以轻松地更改使用这个别名的所有元素的颜色

这是我在tailwind.config.js中尝试做的事情

    module.exports = {
      content: ['./src/**/*.{js,jsx,ts,tsx}'],
      important: '#root',
      theme: {
        colors: {
          ...myColors, //来自设计系统
        },
        extend: {
          colors: {
            // 这行不起作用 :(
            customColor: 'primary-50', //primary-50是来自设计系统导入的令牌。
          },
    ...

在像这样做了某些操作之后我在元素上可以像这样使用颜色

    <div className="bg-customColor">我的元素</div>
    //而不是这样:
    <div className="bg-primary-50">我的元素</div>
是否有办法做类似的事情还是我必须在我的 `index.css` 中创建一个特殊的类然后使用它
英文:

I am importing a bunch of color-tokens from our designsystem. I want to give an alias to one of these colors so that I can easily change the color of all the elements that use this alias.

Here is what I'm trying to do in my tailwind.config.js:

module.exports = {
  content: [&#39;./src/**/*.{js,jsx,ts,tsx}&#39;],
  important: &#39;#root&#39;,
  theme: {
    colors: {
      ...myColors, //From design system
    },
    extend: {
      colors: {
        // This doesn&#39;t work :(
        customColor: &#39;primary-50&#39;, //primary-50 is a token that comes from the designsystem import.
      },
...

After doing something like this I was thinking that I could use the color like so on my elements:

&lt;div className=&quot;bg-customColor&quot;&gt;My element&lt;/div&gt;
//instead of this:
&lt;div className=&quot;bg-primary-50&quot;&gt;My element&lt;/div&gt;

Is there any way to do something like this? Or do I have to create a special class in my index.css that I'll have to use instead?

答案1

得分: 0

搞定了。Tailwind 生成了一堆 CSS 变量,你可以引用它们而不是 tailwind-token:

module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  important: '#root',
  theme: {
    colors: {
      ...myColors, //来自设计系统
    },
    extend: {
      colors: {
        // 这样就可以了! :)
        customColor: 'var(--color-primary-50)',
      },
    ...
英文:

Figured it out. Tailwind creates a bunch of css-variables which you can reference instead of the tailwind-token:

module.exports = {
  content: [&#39;./src/**/*.{js,jsx,ts,tsx}&#39;],
  important: &#39;#root&#39;,
  theme: {
    colors: {
      ...myColors, //From design system
    },
    extend: {
      colors: {
        // This works! :)
        customColor: &#39;var(--color-primary-50)&#39;,
      },
...

huangapple
  • 本文由 发表于 2023年3月9日 22:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定