DEV Community

Pramod Kumar
Pramod Kumar

Posted on

Setting up Tailwind CSS in React with Vite

TailwindCSS has nowadays become the best solution for styling web applications. I started using it some months back and I just love the flexibility it gives.
In this post, I will show how you can easily set tailwindCSS up and start using in React applications.

I am using Vite CLI to create all my new React applications. Vite is a code build tool created on top of rollup. It provides a cli to create any kind of web application (React, Vue, Solid etc). It has a better performance than CRA or even manually set webpack project. Also hot code replacement is very fast. Below image shows the steps to create the React application.

Image description

Image description

Once you have application up, you can follow the below steps.

Below video also walks you through the same steps of setting up tailwindCSS.

  1. Install tailwindcss and autoprefixer as dev-dependencies.
    npm i tailwindcss autoprefixer --save-dev
    Autoprefixer - This is a postCSS plugin which upon code build, adds vendor prefix to some CSS rules. There are few style attributes which need -webkit or -moz prefix for Chrome and Mozilla browsers. Autoprefixer takes care of them.

  2. Run below command to initialize tailwindcss
    npx tailwindcss init -p
    This will create 2 files

postcss.config.js (-p helps to create this file)
Image description

tailwind.config.js
Image description

  1. In tailwind.config.js, update the content value with the path which contains the tsx,jsx files. Only the file path mentioned here will be considered by tailwindCSS.
    content: ["./src/**/*.{js,jsx,ts,tsx}"],
    If any changes are to be done to exisiting properties of tailwind, you can add them in theme section.

  2. Open App.css or index.css and add
    @tailwind base;
    @tailwind components;
    @tailwind utilities;

You are ready to use tailwind css classNames in your code now.
If you are using VS code, you can also install an extension "Tailwind CSS Intellisense" which will help in auto suggesting the classNames.
Image description

You are all set. Happy Coding.

Top comments (0)