I have a card component:
<template>
<div
class="z-50 flex w-[15vw] flex-col items-center justify-center gap-5 rounded-md border-2 border-gray-300 bg-[#f3f3f3] p-5 transition-all duration-300 hover:scale-105 hover:font-bold"
>
<div class="w-[100%]">
<div
:class="color"
class="flex w-fit items-center justify-center rounded-3xl px-2 text-sm text-white"
>
{{ collection }}
</div>
</div>
<div
class="flex w-[100%] flex-col items-center justify-center gap-2 text-2xl font-thin text-black"
>
<div class="italic">{{ question }}</div>
<div class="w-[100%] rounded-3xl border-2 border-gray-200"></div>
<div class="font-semibold">{{ answer }}</div>
</div>
</div>
</template>
<script setup>
const props = defineProps({
collection: String,
question: String,
answer: String,
color: String
})
</script>
<style lang="scss" scoped></style>
and how i use it:
<UsersFavoriteCard
:color="color"
collection="AsyncJs"
question="does it work"
answer="yes"
></UsersFavoriteCard>
const color = computed(() => {
const colors = ['orange', 'blue', 'green', 'amber', 'rose', 'teal']
const randomColor = colors[Math.floor(Math.random() * colors.length)].toLocaleLowerCase()
const randomRange = 300
const color = `bg-${randomColor}-${randomRange}`
console.log(color)
return color
})
the function works, fine, it generatas for example:
bg-red-300
bg-blue-300
bg-amber-300
but from all of the color, only blue and green are applied.
So if i load the page and the color is:
bg-blue-300 or bg-green-300
the card element has this color.
but when the output is bg-red-300 or bg-rose-300 which are valid tailwind colors, the element has no color and i have to refresh the page so the blue or green are choosen.
If i manually set color to
color=’bg-red-300′
it works.
Why it is so inconsistent? Why valid tailwind color generated by function doesnt work, but set manually works but green and blue works all the time?
I tried many examples using tailwind colors, but all set manually works, but generated by functions it doesnt.
2
Answers
As per the documentation:
You could consider one of the following methods to rectify your predicament:
Use full class names in definitions, like:
Safelist the classes you might use like:
Or
The way Tailwind CSS works, it only scans and compiles readily available class names (official docs reference). So essentially, it does not recognize your:
Going by your implementation, I can see you want to randomly pick from your array of colors and use the 300 palette variant. My advice is to use the Tailwind Safelist feature, so that Tailwind can always compile those colors in the final CSS file by default. Here’s what you need to add to your
tailwind.config.js
Hopefully this helps.