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>
Reference:
TailwindCSS configuration reference
Share "How to use CSS variables in TailwindCSS?"
Related snippets:
- Create blinking background with TailwindCSS
- Create a neon effect with TailwindCSS
- Rotate element with TailwindCSS
- Change SVG icon color with TailwindCSS
- Using :not in TailwindCSS
- Specify exact width value in TailwindCSS
- Set element width over 100% using Tailwind CSS
- Stretch children to fill horizontally
- Create a fixed navbar with TailwindCSS
- Use font from local files in TailwindCSS
- Make an element invisible in mobile size in Tailwind CSS
- Create a 20/80 grid with Tailwind CSS
- Select the nth child in TailwindCSS
- Add class to child when hovering on parent in TailwindCSS
- Fill the full height of the screen in TailwindCSS
- Create transition with TailwindCSS
- Create horizontal rule with text using TailwindCSS
- Set background image with TailwindCSS
- How to use CSS variables in TailwindCSS
- Center an absolute element in TailwindCSS
- Remove arrows from number input in TailwindCSS
- How to use !important in TailwindCSS
- Select first child in TailwindCSS
- Access child elements in TailwindCSS
- Create semi transparent background in TailwindCSS
- How to use calc() in TailwindCSS
- Add text shadow with Tailwind CSS
Tags:
use, custom, css, variable, tailwind, tailwindcss Technical term:
How to use CSS variables in TailwindCSS