Hi,
Is it possible to make a custom prefix for utility classes based on a global body class?
For example: i'd like to style a button like so:
<button class="bg-teal-300 dark:bg-teal-800">...</button>
and the dark:bg-teal-800 class should only be applied if the <body> tag has a specific class:
<body class="darkmode">
So generated css should look like this:
.darkmode .dark\:bg-teal-800, .darkmode.dark\:bg-teal-800 {
background-color: #285e61;
}
alternatively you could add the class to the html tag to avoid the duplicate selector. Then the generated css could like a lot cleaner:
.darkmode .dark\:bg-teal-800 {
background-color: #285e61;
}
Yep you can accomplish this using a custom variant:
https://tailwindcss.com/docs/plugins#basic-variants
This plugin looks like what you want basically:
ok thanks!
For anyone stumbling upon this thread, this is my finished config:
module.exports = {
theme: {
extend: {}
},
variants: {
backgroundColor: ['responsive', 'hover', 'focus', 'dark'],
borderColor: ['responsive', 'hover', 'focus', 'dark'],
textColor: ['responsive', 'hover', 'focus', 'dark']
},
plugins: [
function({ addVariant, e }) {
addVariant('dark', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.darkmode .${e(`dark${separator}${className}`)}`
})
})
}
],
};
@justijndepover I did something similar, but do you know how to get things working like dark:hover:bg-teal-800?
This is my plugin structure:
// Add theme mode variant plugin (dark & light mode)
function({ addVariant, e }) {
addVariant("mode-dark", ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.mode-dark .${e(`dark${separator}${className}`)}`;
});
});
addVariant("mode-light", ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.mode-light .${e(`light${separator}${className}`)}`;
});
});
},
Take a look at the plugin Adam mentioned: They made another variant for hover states:
addVariant('dark-hover', ({modifySelectors, separator}) => {
modifySelectors(({className}) => {
return `${darkSelector} .${e(`dark-hover${separator}${className}`)}:hover`;
});
});
That totally makes sense, thanks!
Eventually I want to make it possible to "stack" variants like that in a more generalized way:
Most helpful comment
For anyone stumbling upon this thread, this is my finished config: