skip to Main Content

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


  1. As per the documentation:

    The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

    If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

    Don’t construct class names dynamically

    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    

    In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes.
    Instead, make sure any class names you’re using exist in full:

    Always use complete class names

    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
    

    You could consider one of the following methods to rectify your predicament:

    • Use full class names in definitions, like:

      const color = computed(() => {
        const colors = ['bg-orange-300', 'bg-blue-300', 'bg-green-300', 'bg-amber-300', 'bg-rose-300', 'bg-teal-300']
        const randomColor = colors[Math.floor(Math.random() * colors.length)].toLocaleLowerCase()
        console.log(color)
        return color
      })
      
    • Safelist the classes you might use like:

      /** @type {import('tailwindcss').Config} */
      module.exports = {
        safelist: [
          'bg-orange-300',
          'bg-blue-300',
          'bg-green-300',
          'bg-amber-300',
          'bg-rose-300',
          'bg-teal-300'
        ],
        // …
      }
      

      Or

      /** @type {import('tailwindcss').Config} */
      module.exports = {
        safelist: [
          {
            pattern: /^bg-(orange|blue|green|amber|rose|teal)-300$/,
          },
        ],
        // …
      }
      
    Login or Signup to reply.
  2. The way Tailwind CSS works, it only scans and compiles readily available class names (official docs reference). So essentially, it does not recognize your:

    bg-${randomColor}-${randomRange}
    

    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

           module.exports = {
              // other config options here...
              safelist: [
                'bg-orange-300',
                'bg-blue-300',
                'bg-green-300',
                'bg-amber-300',
                'bg-rose-300',
                'bg-teal-300',
               // You can add more Tailwind classes you wish to compile by default e.g lg:text-red-100, md:justify-center, etc. 
               // Just about any Tailwind classname really...
              ]
            }
    

    Hopefully this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search