Vue + Tailwind and Dynamic Classes
Andrew Bell
Posted on October 8, 2024
A project I've been working on recently makes use of Vite, Vue and Tailwind.
After some time working with custom colors, I faced some confusion.
Adding and using the custom colors in a template, was not the issue - the process is made very clear using the Tailwind Documentation
// tailwind.config.js
module.exports = {
theme: {
colors: {
'custom-green': {
50: '#9bd1b2',
...
700: '#284735'
},
}
}
}
My issue was when using the custom colors with dynamic and static css classes in the Vue template.
When running the project with npm run dev
or vite
the bg-custom-green-50
or text-custom-green-50
did not work and never appeared in the css files.
My understanding is if your full css class name does not exist in the template then tailwind will not add it or generate it in the css file.
Assuming the css classes: text-custom-green-50
or bg-custom-green-50
are not used anywhere else in the project
The example below will not work
<template>
<h3 :class="['font-bold', colorClass]">{{ heading }}</h3>
</template>
<script type="text/javascript">
const colorClass = ref('')
// color being set somewhere else in the component logic
colorClass.value = 'text-custom-green-50'
</script>
The example below will work
<template>
<h3 :class="['font-bold', colorClass]">{{ heading }}</h3>
<p class="text-custom-green">Green text</p>
</template>
<script type="text/javascript">
const colorClass = ref('')
// color being set somewhere else in the component logic
colorClass.value = 'text-custom-green-50'
</script>
The difference between the two examples is the text-custom-green
css class is added to the template so tailwind will add it to the generated css file.
To overcome this you can add any custom colors or tailwind classes to a safelist
within your tailwind.config.js file.
// tailwind.config.js
module.exports = {
safelist: [
'text-custom-green-50',
'bg-custom-green-50'
]
}
These colors will be available even if they are not used directly in a template, but added dynamically at another point
Hopefully someone else finds this helpful.
Posted on October 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.