csstailwind-css

How to use CSS variables with Tailwind CSS


Is it possible to use CSS variables with Tailwind CSS? For instance, let's say I have these variables:

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

And I would like to use them in Tailwind like so:

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

How can I achieve that?


Solution

  • Assuming you have already added TailwindCSS to your project and that your CSS file is called global.css.

    First, you need to edit global.css to look like this:

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    .root,
    #root,
    #docs-root {
      --primary-color: #fff;
      --secondary-color: #000;
    }
    

    And then, in order to be able to use them, you need to update tailwind.config.js with the new CSS variables like so:

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

    You can now use these variables as desired:

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