0
0
Tailwindmarkup~5 mins

CSS variables with Tailwind

Choose your learning style9 modes available
Introduction

CSS variables let you store colors or sizes once and reuse them everywhere. Tailwind works well with these variables to keep your design consistent and easy to change.

You want to change a color theme quickly across your whole site.
You need to reuse the same spacing or font size in many places.
You want to create a dark mode by switching variable values.
You want to keep your Tailwind styles clean and easy to update.
You want to share design values between CSS and Tailwind utilities.
Syntax
Tailwind
:root {
  --main-color: #4f46e5;
}

.element {
  color: var(--main-color);
}

/* In Tailwind config or classes, use the variable */
.text-main {
  color: var(--main-color);
}
Define CSS variables inside :root to make them global.
Use var(--variable-name) to access the variable value.
Examples
This example sets a blue color as a CSS variable and uses it in a Tailwind-like class.
Tailwind
:root {
  --primary: #3b82f6;
}

.text-primary {
  color: var(--primary);
}
Here, a spacing variable is used for margin-top to keep spacing consistent.
Tailwind
:root {
  --spacing: 1.5rem;
}

.mt-custom {
  margin-top: var(--spacing);
}
Tailwind allows using arbitrary values like text-[var(--primary)] to apply CSS variables directly.
Tailwind
<div class="text-[var(--primary)]">
  Hello with CSS variable color
</div>
Sample Program

This page uses CSS variables for color and padding. Tailwind applies the padding using the variable and the heading color uses the variable with an arbitrary value.

Tailwind
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>CSS Variables with Tailwind</title>
  <style>
    :root {
      --main-color: #ef4444; /* red */
      --main-padding: 1rem;
    }
  </style>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="p-[var(--main-padding)]">
  <h1 class="text-[var(--main-color)] font-bold text-3xl">
    Hello with CSS Variables and Tailwind
  </h1>
  <p class="mt-4 text-gray-700">
    This text uses Tailwind spacing and a CSS variable for color.
  </p>
</body>
</html>
OutputSuccess
Important Notes

You can change the CSS variable in :root to update colors or spacing everywhere instantly.

Tailwind's arbitrary value syntax like text-[var(--main-color)] lets you use CSS variables directly in your classes.

Remember to include the Tailwind CDN or build Tailwind in your project to use these utilities.

Summary

CSS variables store reusable values like colors or spacing.

Tailwind supports CSS variables using arbitrary value syntax.

Using variables keeps your design consistent and easy to update.