Setting Up a New Tailwind CSS 4.x Project

Published:

tailwindcss 4.0 has been officially released, and the installation process has changed a bit. The good news is that it is noticeably simpler than before. The official documentation already explains the setup, but if you prefer a slightly adjusted workflow for a plain project, the following steps are a straightforward way to get started.

Install Tailwind CSS

Install tailwindcss with npm. In Tailwind CSS 4.x, the CLI is installed separately, so both packages are needed here:

npm install tailwindcss @tailwindcss/cli

Add the Tailwind directive to your CSS file

Create a CSS file wherever it makes sense for your project. For example, you can create src/main.css, then put the following content inside it:

@import "tailwindcss";

That is enough for Tailwind 4.x to load its styles through this entry file.

Use Tailwind in your HTML

After compiling the CSS, include the generated CSS file in the <head> of your HTML page. Then you can start using Tailwind utility classes directly in your markup.

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="/src/tw.css" rel="stylesheet">
</head>
<body>
  <h1 class="text-3xl font-bold underline">
    Hello world!
  </h1>
</body>
</html>

Add a build command

Initialize a package.json file first:

npm init -y

Then open package.json and add a script like this:

"scripts": {
  "build": "tailwindcss -i ./src/main.css -o ./src/tw.css --watch"
}

Now you can run:

npm run build

This command watches your page changes and recompiles the CSS automatically.

Auto-refresh HTML while editing

This part is not really related to Tailwind CSS itself, but it is useful when working on static pages. If you want the browser preview to refresh automatically whenever an html file changes, install the Live Preview extension in vscode.

After installing it, open the page you want to preview, right-click in the editor, and choose Live Preview:Show Preview.

Generate a minified CSS file

If you want to output a minified version of the CSS, add a minify build script. The script can be arranged like this:

  "scripts": {
    "build:css": "tailwindcss -i ./src/main.css -o ./src/tw.css",
    "build:css:min": "tailwindcss -i ./src/main.css -o ./src/tw.min.css --minify --watch",
    "build": "npm run build:css:min"
  },

With this setup, npm run build will run the minified build command and keep watching for changes.