Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Armando Guarino Avatar asked Nov 17 '20 09:11

Armando Guarino


People also ask

Can you use CSS and Tailwind together?

In this article, we will know how to use Bootstrap with Tailwind CSS, at a moment, in the same code. We can use both the CSS frameworks together but it is not recommended. Because few classes will contradict with each other like “container”, “clearfix”, etc. As we know that Bootstrap is a known CSS framework.

How do we use CSS variables?

To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.


Video Answer


3 Answers

Armando's answer didn't work for me but with this change it did work.

global.css:

no need to target a class or id. you can target the root itself using the Pseudo-Selector https://www.w3schools.com/cssref/sel_root.asp

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

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

as for tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      colors: {
        "primary-color": "var(--primary-color)",
        "secondary-color": "var(--secondary-color)"
      },
    },
  },
};
like image 141
Ahmed Essam ElDessouki Avatar answered Oct 13 '22 14:10

Ahmed Essam ElDessouki


Now Tailwind supports CSS custom properties as arbitrary values since v3.0.

: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>
like image 44
doğukan Avatar answered Oct 13 '22 16:10

doğukan


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>
like image 8
Armando Guarino Avatar answered Oct 13 '22 14:10

Armando Guarino