The Vue.js component exclusively displays background colors selected from a limited range of Tailwind CSS colors

I am currently working with 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>

Here is an example of how I use it in my project:

   <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
})

After testing the function, it successfully generates colors such as: bg-red-300 bg-blue-300 bg-amber-300

However, there seems to be some inconsistency where only blue and green colors are being applied. For example, if the generated color is: bg-blue-300 or bg-green-300

the card element displays correctly with that color. But when the output is bg-red-300 or bg-rose-300, which are valid Tailwind colors, the element appears without any color until the page is refreshed to display either blue or green. Manually setting the color to color='bg-red-300' works without issues. Why does this inconsistency occur? Why do valid Tailwind colors generated by the function fail to work while manually set colors like blue and green always work?

I have experimented with various examples using Tailwind colors, and consistently found that manually set colors work, but those generated by functions do not.

Answer №1

According to the official documentation:

An important factor to note about how Tailwind extracts class names is that it will only detect classes that appear as complete unbroken strings in your source files.

If you attempt to use string interpolation or combine partial class names, Tailwind will not be able to identify them and therefore won't generate the corresponding CSS:

Avoid constructing dynamic class names

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

In the given example, the classes text-red-600 and text-green-600 do not exist, so Tailwind will skip generating those classes. Ensure that all class names being used are complete:

Always utilize full class names

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

You have a few options available to resolve this issue:

  • Employ entire class names in definitions, for instance:

    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
    })
    
  • Include the classes in safelist that might be utilized 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$/,
        },
      ],
      // …
    }
    

Answer №2

When it comes to Tailwind CSS, it operates by scanning and compiling available class names only (official documentation reference). Therefore, it does not recognize the following:

bg-${randomColor}-${randomRange}

Based on your code snippet, it seems like you intend to randomly select colors from an array and use the 300 palette variant. My suggestion is to utilize the Tailwind Safelist feature. This way, Tailwind will always include those colors in the final CSS file by default. Here's what needs to be added to your tailwind.config.js:

module.exports = {
    // other configuration 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 that you want to compile by default e.g lg:text-red-100, md:justify-center, etc.
        // Essentially any Tailwind classname...
    ]
}

I hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Upon clicking the button, an event listener is attached to the window

I have an image with an onClick function attached to it. <img className="pointer pipette-icon" src={pipetteIcon} alt="" onClick={handlePipetteClick} /> My objective is as follows: when clicking on this image, nothing should happe ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

Is it possible to utilize multiple .html files in a single view while incorporating Materialize?

Within my AngularJS application that utilizes Materialize, I have a module called "reports" containing a view called "reports.html" intended to house all of my reports. However, I desire to separate the code for each report into individual .html files, suc ...

Troubleshooting a Navbar Issue in a Custom Bootstrap Template

I am a beginner in html and bootstrap, but I recently attempted to create my own bootstrap template. Initially, I tried to work with the "starter template" code from getbootstrap.com, but after launching the code and making some changes, the navigation bar ...

User interface design for node.js and jquery web applications

When using node.js for web applications, is there a preferred UI framework to pair with it? Or is this an independent consideration? While jQuery is popular, is jQuery UI the most commonly used UI framework with the jQuery engine? Ar ...

Center the table cell element horizontally

Struggling to align a table cell element both horizontally and vertically? Currently, only managing the vertical alignment. The images vary in size, calling for fluidity and compatibility with max-height and width... Custom Style Sheet (CSS) .prod-img { ...

Display or conceal a div based on the input value

Displaying div#cool should be triggered when the user enters the term "cool" into the input field. Similarly, showing div#good should be activated when the user types "good", and this functionality should operate seamlessly in real-time. ...

Make sure to trigger $emit after executing the dispatch action in Vuejs

I am working on a parent component: <template> <div class="w-full"> <div class="card-body"> <city-edit-form :form="form" :resource="resource" @save_resource="func"> </city-edit-form> ...

Make sure to retain PHP includes/requires when dynamically loading a new page using AJAX

My website has a main page with a header, navbar, footer, and content is loaded using AJAX into a div: <div id="content" class="page-content"></div> I am wondering if it's feasible to load a page dynamically into the content div using AJA ...

Rapache and R team up for dynamic leaflet design

I'm currently working on creating a webpage using Rapache and "Leaflet for R". My main goal is to integrate R into an html page using brew. However, I am facing difficulties in displaying my map within the html page without having to save it as an ext ...

Global asynchronous functionality can be enabled in JavaScript

Wouldn't it be convenient to have the option to enable async functionality in the global scope? This way, there would be no need to wrap all asynchronous operations within a function. I'm curious if this is achievable in browser JavaScript or per ...

The program suddenly halts during the second loop without displaying any error messages

I've encountered an issue with my Node.js program on Windows that records microphone sound. The problem arises when I try to record multiple .wav files within a loop while taking user options from a menu. Initially, everything works fine and the prog ...

Place the written content within a spinner on a Bootstrap framework

I have successfully implemented a Bootstrap 4.3 spinner on my website, but I am encountering an issue where I want to add additional text below the spinner. Here is the HTML code I am using: <div class="d-flex justify-content-center"> <d ...

Can we safely assume in JavaScript that the "constructor" property exists on variables with values that are not "null" or "undefined"?

Is it a safe bet to assume that every variable in JavaScript will have a "constructor" property as long as its value isn't "null" or "undefined"? I recently encountered a scenario where I needed to confirm whether a variable is defined, if it's ...

Having trouble converting a JSON object to JavaScript properly? The issue may lie in how the JSON is being passed from PHP to AJAX

I've spent countless hours searching for a solution to this problem by browsing through similar questions and answers, but I haven't had much success... In my PHP code, I used json_encode($Final_info); to convert a PHP array into a JSON object, ...

Extension for Chrome - view source of current webpage

I'm attempting to develop my chrome extension to extract the current page source and identify the current URL, as seen in this example. If I were to visit https://www.google.com and the page source contains google I want my extension to display a ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...

Can anyone provide guidance on displaying a JS alert every time a tab in the slider is opened?

Utilizing the liquidslider script on my website, I have created a slider with the following HTML code: <div class="liquid-slider" id="slider-id"> <div> <h2 class="title">Slide 1</h2> // Content goes here ...

Deliver a message using a loop in jade

I'm struggling with posting a request in Node and Jade using a specific ID. For instance, if Node returns a list of books : res.render('tests', {books: books}); In my Jade template, I display all the books by iterating through them. b ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...