11

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

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

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

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

我怎样才能做到这一点?

4

5 回答 5

17

Armando 的回答对我不起作用,但有了这个改变,它确实起作用了。

global.css

无需定位类或 id。您可以使用 Pseudo-Selector 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)"
      },
    },
  },
};
于 2021-02-23T12:59:40.507 回答
7

现在 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>

于 2021-12-10T06:03:37.427 回答
5

假设您已经将 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>
于 2020-11-17T09:51:12.943 回答
2

您可以使用此插件轻松配置它。(支持暗模式)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
}
于 2021-04-06T20:28:25.960 回答
0

来自官方 Tailwind 文档:

:root {
  --theme-color: #52b3d0;
}

/* ... */

.btn {
  background-color: var(--theme-color);
  /* ... */
}
于 2021-12-24T12:15:25.467 回答