SmartCodingTips

Using :root CSS Variables in Tailwind

You can integrate native CSS variables using the :root selector and combine them with Tailwind classes for **dynamic theming** and **maintainability**.

1. Define Variables in :root

Add custom variables in your global CSS:


:root {
  --primary-color: #0084ff;
  --accent-color: #3AB0FF;
  --font-heading: 'Poppins', sans-serif;
}
            

2. Use in Tailwind with Arbitrary Values

Use Tailwind's support for arbitrary values like:


<button class="bg-[var(--primary-color)] text-white px-4 py-2 rounded">
  Click Me
</button>

<h1 class="text-3xl font-[var(--font-heading)]">
  Dynamic Heading
</h1>
            

This allows full design control while keeping your HTML clean and reusable.

3. Change Theme with JavaScript

Use JS to change themes dynamically:


document.documentElement.style.setProperty('--primary-color', '#16a34a'); // green-600
            

4. Tips and Use Cases

  • Great for **theming**, especially dark/light modes
  • Useful for **brand-based colors** across large projects
  • Use Tailwind + `:root` for design tokens
  • Combine with data-theme attributes for theme switching

Conclusion

Combining Tailwind with native CSS variables gives you scalable, dynamic styling power — blending utility-first classes with themable flexibility.