Open In App

How to build classnames dynamically in Tailwind CSS ?

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Popular CSS framework Tailwind CSS offers pre-defined classes for rapid web page decorating. Its ability to dynamically generate class names based on configuration parameters is one of its primary characteristics, making it simple to develop responsive layouts without using bespoke CSS styles. The goal of this post is to clearly explain the syntax and methods for dynamically creating class names in Tailwind CSS, as well as present examples that show how to make advantage of this feature to create responsive layouts.

In this article, we will explore how to dynamically build class names in Tailwind CSS. We will discuss the syntax and different approaches to generating class names, along with examples of how you can use this feature to build responsive layouts

Syntax: The syntax for dynamically generating class names in Tailwind CSS follows the format:

{{prefix}}-{{value}}-{{suffix}}

 

Where:

  • prefix: This is an optional prefix that can be added to the class name. It is typically used to group related classes together, such as sm: for small screens, md: for medium screens, and lg: for large screens.
  • value: This is the value that defines the style or behavior of the class. For example, text for text color, bg for background color, flex for flexbox layout, etc.
  • suffix: This is an optional suffix that can be added to the class name. It is typically used to specify a modifier or variation of the base class, such as hover, focus, active, etc.

Approaches: There are several approaches to dynamically generating class names in Tailwind CSS:

  • Using configuration variables: TailwindCSS provides a set of configuration variables that can be used to customize the generated class names. For example, you can define custom breakpoints for different screen sizes, customize the font sizes and colors, and much more.
  • Using utility functions: TailwindCSS also provides a set of utility functions that can be used to generate class names programmatically. These functions allow you to dynamically generate class names based on user input or state changes.
  • Using custom plugins: TailwindCSS allows you to create custom plugins that extend its functionality. You can use these plugins to generate custom class names that are specific to your application’s needs.
     

Example 1: Using JavaScript Template Literals

In this example, we will use JavaScript Template Literals to dynamically build class names based on a variable value. We will create a simple div element that changes its background color based on the value of a variable bgColor.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href=
    <style>
        .red {
            background-color: red;
        }
  
        .blue {
            background-color: blue;
        }
  
        .green {
            background-color: green;
        }
    </style>
</head>
  
<body>
    <div class="py-4">
        <div class="h-32 w-32 ${bgColor}">
        </div>
    </div>
  
    <script>
        let bgColor = "red";
        const element = document.querySelector('.h-32');
        element.classList.remove('red', 'blue', 'green');
        element.classList.add(bgColor);
    </script>
</body>
  
</html>


Output:

Dynamically build classnames in TailwindCSS

Dynamically build classnames in TailwindCSS

In this example, we use JavaScript Template Literals to insert the value of the bgColor variable into the class name of the div element. We define three different classes in the stylesheet with different background colors: .red, .blue, and .green. The bgColor variable is initially set to red, but it can be changed to blue or green to see different colors.

In the JavaScript code, we select the div element using querySelector and remove any existing color classes using classList.remove. We then add the appropriate class based on the value of bgColor using classList.add.

Example 2: Using JavaScript Array and Loops

In this example, we will use a JavaScript array and loop to dynamically build class names for a div element. We will create a simple div element that has a gradient background color based on an array of color values.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href=
</head>
  
<body>
    <div class="h-32 w-32">
    </div>
  
    <script>
        const colors = [
            'bg-red-500', 
            'bg-yellow-500', 
            'bg-green-500', 
            'bg-blue-500', 
            'bg-purple-500'
        ];
  
        const element = document.querySelector('.h-32');
  
        let i = 0;
          
        setInterval(() => {
            element.classList.remove(...colors);
            element.classList.add(colors[i]);
            i = (i + 1) % colors.length;
        }, 1000);
    </script>
</body>
  
</html>


Output:

Dynamically build classnames in TailwindCSS

Dynamically build classnames in TailwindCSS

In this example, we define an array of TailwindCSS utility classes with different background colors: bg-red-500, bg-yellow-500, bg-green-500, bg-blue-500, and bg-purple-500. We then select the div element using querySelector and store it in a variable called an element.

Next, we use a setInterval function to change the background color of the div element every second. Inside the interval function, we remove all the color classes from the div element using classList.remove and add the next color in the array using classList.add. We use the `%` operator to ensure that the index `i` always stays within the bounds of the array.

By using an array and loop, we can easily add or remove colors to the gradient by modifying the colors array. This allows for more flexibility and dynamicity in building class names in TailwindCSS.
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads