Sonali
Sonali

Reputation: 21

How to add tw- prefix to Tailwind CSS classes in a React Vite project with Tailwind CSS v4?

I’m working on a React project using Vite and Tailwind CSS v4. I want to add the tw- prefix to all Tailwind CSS classes

I tried adding the following line to my index.css file:

@import "tailwindcss" prefix(tw);

However, it doesn't work, and I am getting the following error:

semi-colon expectedcss(css-semicolonexpected)

How can I correctly add the tw- prefix to all Tailwind classes in my setup? Is there a different way to achieve this in Tailwind CSS v4 since the tailwind.config.js file is no longer required?

Upvotes: 2

Views: 1593

Answers (1)

rozsazoltan
rozsazoltan

Reputation: 9073

Starting from TailwindCSS v4, class names are no longer extended; instead, the prefix appears as a main utility. It must be applied before everything else. The goal is to make it easier to distinguish TailwindCSS class names from custom class names when reading the code.

From TailwindCSS v4 onwards

If you use a prefix, the following is valid. The prefix should be connected with a colon (:) rather than a hyphen (-). Additionally, the prefix should always be used as the first utility. By default, this would be tw:content, but due to other utilities, you need to gradually place the appropriate utilities in between.

@import "tailwindcss" prefix(myprefix);
myprefix:text-red-500
myprefix:hover:text-red-500

Until TailwindCSS v3

Until v3, prefixes had to be specified in the legacy JavaScript-based configuration. They did not function as utilities but were prepended to the original class name, independent of other utilities.

/** @type {import('tailwindcss').Config} */
export default {
  prefix: 'myprefix-',
}
myprefix-text-red-500
hover:myprefix-text-red-500

Upvotes: 3

Related Questions