Home >Web Front-end >JS Tutorial >How to Use Dynamic Class Names with Tailwind CSS?

How to Use Dynamic Class Names with Tailwind CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 10:01:11817browse

How to Use Dynamic Class Names with Tailwind CSS?

Dynamic Class Names and Tailwind CSS

Dynamically constructing class names in JavaScript is a common practice, but when it comes to Tailwind CSS, it poses a challenge. Tailwind CSS relies on extracting complete unbroken class names from your source files.

As per Tailwind's documentation, dynamically constructing class names using string interpolation or concatenation will result in Tailwind not finding the classes and therefore not generating the corresponding CSS. For instance:

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

In this example, the text-red-600 and text-green-600 strings don't exist as complete class names, so Tailwind ignores them.

Solutions:

To address this issue, there are several solutions:

  • Use Complete Class Names:
    Ensure that any class names you use exist in their complete form.
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
  • Define Class Names in Variables:
    Define the class names in variables that can be directly referenced.
const colors = {
  // ...
  secondary: darkTheme ? "bg-[#FFFFFF]" : "bg-[#FFFFFF]",
  // ...
};
<p className={`${colors.secondary} text-text-white`}></p>
  • Utilize the style Attribute:
<p className="text-text-white">

The above is the detailed content of How to Use Dynamic Class Names with Tailwind CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn