Reputation: 7007
I am trying to modify the tailwind.config.js
file to create some custom classes. For example, I would like to create a color palette - and do so by referencing other colors in the theme.
To do so, I have made the following changes to the tailwind.config.js
file:
module.exports = {
theme: {
extend: {
colors: {
primary: (theme) => theme("colors.blue.500"),
},
}
...
This, however, does not work. I don't get any errors - but I also do not get any custom classes either (even though, according to the docs, this should work).
On the other hand, this does work:
module.exports = {
theme: {
extend: {
colors: {
primary: "#abcdef",
},
}
...
This will create classes such as bg-primary
.
Any idea how I can create custom classes by referncing other values in the theme?
Thanks.
Upvotes: 5
Views: 5923
Reputation: 396
To reference other values, it has to be in the top-level theme key, instead of individual value. Docs: https://tailwindcss.com/docs/theme#referencing-other-values
For example:
// bad
module.exports = {
theme: {
extend: {
colors: {
primary: (theme) => theme("colors.blue.500"),
},
}
// good
module.exports = {
theme: {
extend: {
colors: ({theme}) => ({
primary: theme("colors.blue.500"),
}),
}.
Upvotes: 2
Reputation: 8540
Your first example indeed doesn't seem to work. These don't work either:
module.exports = {
theme: {
extend: {
colors: (theme) => ({
primary: theme('colors.blue.500'),
})
},
},
}
// → RangeError: Maximum call stack size exceeded
module.exports = {
theme: {
extend: (theme) => ({
colors: {
primary: theme('colors.blue.500'),
}
}),
},
}
// → no error, but doesn't work
module.exports = {
theme: (theme) => ({
extend: {
colors: {
primary: theme('colors.blue.500'),
}
},
}),
}
// → no error, but doesn't work
However, the Customizing Colors page has a section called Overriding a single shade which contains the following example and explanation why your config and my configs above don't work:
Since values in the
theme.extend
section of your config file are only merged shallowly, overriding a single shade is slightly more complicated.The easiest option is to import the default theme and spread in the color you want to customize along with the new shade value:
// tailwind.config.js const { colors } = require('tailwindcss/defaultTheme') module.exports = { theme: { extend: { colors: { blue: { ...colors.blue, '900': '#1e3656', } } } } }
So, here's how you can achieve what you are trying to do:
const { colors } = require('tailwindcss/defaultTheme')
module.exports = {
theme: {
extend: {
colors: {
primary: colors.blue['500'], // 500 (number) would also work
}
}
}
}
I tried this, and it seems to work. The built CSS file contains these classes (among others, of course):
.bg-blue-500 {
--bg-opacity: 1;
background-color: #4299e1;
background-color: rgba(66, 153, 225, var(--bg-opacity));
}
.bg-primary {
--bg-opacity: 1;
background-color: #4299e1;
background-color: rgba(66, 153, 225, var(--bg-opacity));
}
Upvotes: 3