- Instant help with your CSS coding problems

How to use CSS variables in TailwindCSS

Question:
How to use CSS variables in TailwindCSS?
Answer:
/* In CSS */
:root {
  --my-custom-color: #4488cc;
}

/* In tailwind.config.js */
module.exports = {
  theme: {
    extend: {
      colors: {
        "my-custom-color": "var(--my-custom-color)",
      },
    },
  },
 plugins: [],
}
Description:

You can use CSS variables in TailwindCSS eighter using it as an arbitrary value or extending the basic configuration.

First you need to define your variables in global.css like this:

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

:root {
  --my-custom-color: #4488cc;
  --my-other-color: #cc8844;
}

From now you can already use these variables in your code as an arbitrary value. For example:

<div class="bg-[color:var(--my-other-color)] w-32 h-32"></div>

To make the development process more user friendly it can be better to configure Tailwind to use the CSS variables and build a custom color from it. To do this edit the tailwind.config.js file as follows: 

module.exports = {
  theme: {
    extend: {
      colors: {
        "my-custom-color": "var(--my-custom-color)",
      },
    },
  },
 plugins: [],
}

With this configuration set you can write a code like this:

<div class="bg-my-custom-color w-32 h-32"></div>

 

Share "How to use CSS variables in TailwindCSS?"
Interesting things
OpanAi's ChatGPT