- Published on
How to Reference Tailwind Colors in CSS
- Authors
- Name
- Ripal & Zalak
How to Reference Tailwind Colors in CSS
Tailwind CSS provides a flexible color system, but sometimes you may need to use those colors inside your custom CSS files. Here’s how you can reference Tailwind colors in CSS efficiently.
theme()
Function
1. Using the You can use Tailwind’s theme()
function inside your CSS to access colors defined in tailwind.config.js
.
.prose a.custom-link {
color: theme('colors.primary.500');
}
Example Tailwind Config
module.exports = {
theme: {
extend: {
colors: {
primary: {
500: '#0E70ED',
600: '#0552b3',
},
},
},
},
}
@apply
2. Using If you are inside a CSS file processed by Tailwind, you can use @apply
.
.prose a.custom-link {
@apply text-primary-500;
}
3. Using Tailwind Colors in JavaScript
To access Tailwind colors in JavaScript, use resolveConfig
:
import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from '@/tailwind.config.js'
const twFullConfig = resolveConfig(tailwindConfig)
console.log(twFullConfig.theme.colors.primary[500])
4. Using CSS Variables for Tailwind Colors
You can define CSS variables inside tailwind.config.js
and use them globally.
globals.css
Update :root {
--primary: theme(colors.primary.500);
--secondary: theme(colors.primary.600);
}
Use in Tailwind Config
module.exports = {
theme: {
extend: {
colors: {
primary: 'var(--primary)',
secondary: 'var(--secondary)',
},
},
},
}
Use in CSS or Components
body {
background-color: var(--primary);
color: var(--secondary);
}
Or inside JSX/HTML:
<div class="bg-primary text-secondary">Hello Tailwind</div>
FAQs
1. Can I use Tailwind colors in inline styles?
No, Tailwind's theme()
function requires PostCSS processing. Instead, define CSS variables or use resolveConfig
in JavaScript.
2. Can I use Tailwind colors outside Tailwind’s build system?
Yes, by using theme()
, @apply
, or defining CSS variables as shown above.
3. Why should I use CSS variables with Tailwind?
Using CSS variables ensures consistency across Tailwind styles and custom styles, making it easier to maintain brand colors.