Set up Tailwind CSS in Hugo

Tailwind and Hugo work well together, but Hugo still needs a CSS build step. The simplest option is the Tailwind CLI; PostCSS is useful when the project already depends on other PostCSS plugins.

This article reflects the Tailwind setup used when it was written in 2022. Tailwind’s CLI and configuration have changed since then, so check the documentation for the version installed in your project before copying the commands.

You will need Hugo and Node.js installed. Run the following commands from the root of the Hugo project.

Set up the Tailwind CLI

Install Tailwind:

npm install tailwindcss

Create its configuration file:

npx tailwindcss init

This creates tailwind.config.js in the project root. Configure its content paths for the templates and content files that contain Tailwind classes; otherwise the generated stylesheet may omit classes that the site uses.

Create static/css/main.css with the Tailwind layers:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Link the generated file from the site’s <head>, for example in layouts/partials/head.html:

<link rel="stylesheet" href="/css/main.css">

Then generate the stylesheet:

npx tailwindcss build static/css/main.css -o static/css/main.css

This reads the input file and writes the compiled CSS back to static/css/main.css. Using separate input and output paths is cleaner for a larger project, because generated files do not overwrite their source.

If the project already uses PostCSS

PostCSS makes sense when Tailwind is one part of a longer CSS pipeline. Install the CLI and the plugins used here:

npm install -D postcss-cli
npm install -D postcss-import postcss-preset-env

Create postcss.config.js in the project root:

module.exports = {
  plugins: [
    require('postcss-import'),
    require('postcss-preset-env')({ stage: 0 }),
    require('tailwindcss'),
  ]
}

Keep the Tailwind imports in main.css:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Run the PostCSS build:

npx postcss static/css/main.css -o static/css/main.css

For a small site, I would start with the Tailwind CLI. Add PostCSS only when another plugin or an existing build pipeline gives you a reason to maintain the extra configuration.