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?
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.
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.
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)"
},
},
},
};
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With