Categories
TailwindCSS Vue

Tailwind CSS and Dynamic or Conditional Class Names in Vue

Tailwind CSS is designed to include only the classes used in your project in the final build CSS file. This approach keeps the file size small and optimizes load times.

Tailwind's default configuration processes looks through your files to find all instances of class names and generates the corresponding CSS. If you generate class names dynamically (e.g., using variables or concatenation), Tailwind can't see these classes at build time. Therefore, it doesn't include them in the final CSS, leading to styles not loading and not being rendered as expected.

Problematic Scenarios in Tailwind CSS

  1. Dynamically Created Class Names:
    <div :class="`bg-${color}-500`"></div>
    

    Here, the class name is constructed dynamically based on a variable. Tailwind can't detect these classes at build time since they're not explicitly written in the files.

  2. Conditional Rendering with Ternary Operators:
    <div :class="isActive ? 'bg-green-500' : 'bg-red-500'"></div>
    

    Although the class names are not dynamically generated, they are conditionally applied and not visible as standalone classes in the template.

  3. Array Mapping or Joining:
    <div :class="['bg-blue-500', isActive ? 'bg-green-500' : ''].join(' ')"></div>
    

    The classes are conditionally joined in an array, making it difficult for Tailwind to statically analyze them.

  4. Using Variables for Class Names:
    <div :class="isActive ? activeClasses : inactiveClasses"></div>
    

    If activeClasses and inactiveClasses are defined in the script section or imported, Tailwind can't parse what's inside these variables.

  5. Concatenation in v-bind:
    <div :class="'bg-' + (isActive ? 'green' : 'red') + '-500'"></div>
    

    Similar to dynamic creation, this concatenation makes the class name a computed string, invisible to Tailwind during build.

Solution 1: Explicit Class Names & Using Vue's Object Syntax in v-bind:class:

<div :class="{ 'bg-blue-500': someCondition, 'bg-green-500': anotherCondition }"></div>

This approach allows you to list all potential classes explicitly, with boolean expressions dictating their application. Tailwind can then statically analyze and include these classes.

Solution 2: Safelisting Classes in Tailwind Configuration

For known dynamic classes, you can explicitly include them in the Tailwind configuration.

// tailwind.config.js
module.exports = {
  safelist: ['bg-blue-500', 'bg-green-500', ...],
}

Leave a Reply

Your email address will not be published. Required fields are marked *