Theme Function and Referencing Values
You'll learn how to use Tailwind's theme() function to reference your design tokens consistently across custom CSS and configuration files.
The Problem of Hardcoding Values
When you create custom utilities or write one-off CSS, you might be tempted to hardcode colors, spacing, or other values. But this breaks the connection to your design system. If you later change your brand color in tailwind.config.js, those hardcoded values won't update automatically.
What is the theme() Function?
The theme() function is like a lookup tool that retrieves values from your Tailwind configuration. Think of it as a reference book for your design system—instead of memorizing every value, you simply ask the book.
You can use theme() in two places:
In your tailwind.config.js file:
module.exports = {
theme: {
extend: {
colors: {
brand: '#3b82f6',
},
spacing: {
'custom': theme('spacing.4'), // References spacing.4
}
}
}
}
In your custom CSS layers:
@layer components {
.my-button {
background-color: theme('colors.brand');
padding: theme('spacing.4') theme('spacing.8');
border-radius: theme('borderRadius.lg');
}
}
Dot Notation Path
Use dot notation to navigate nested values: theme('spacing.4'), theme('colors.blue.500'), theme('fontSize.xl'). This ensures your custom code always stays synchronized with your theme configuration.
Key Takeaway: The theme() function keeps your custom CSS and configuration tied to your design system, preventing inconsistencies and making global changes effortless.