Tailwind CSS with Blazor

Sep 18, 2023 /
# Tailwind
# Blazor

There are several ways to utilize Tailwind CSS in a Blazor project. We will cover them from easiest to hardest to implement. Each has it’s own tradeoffs.

Tailwind CSS CDN

The easiest way to start off with Tailwind CSS in your Blazor project is to import the Tailwind CDN.

You can do this by adding the following script tag to the head section in your _Layout.cshtml file.

<!DOCTYPE html>
<html lang="en">
<head>
    ...
    <script src="https://cdn.tailwindcss.com"></script>
    ...
</head>

It is advised to not use the Tailwind CDN in production according to their official docs.

This is because if the CDN goes down your app will no longer have the styles it depends on. It also has a larger download size than if the styles were in a local .css file.

However, if your app is not some mission critical piece for your business, it’s probably ok to use the CDN.

Tailwind CLI

The suggested way to use Tailwind in Blazor according to the tailwind docs is to use the Tailwind CLI.

While more work, this will reduce the download size of your CSS and also remove the dependancy of the CDN link from your app.

Install Tailwind CLI in your project

To do this, first run the following commands:

npm install -D tailwindcss
npx tailwindcss init

Configure template paths

This will install the tailwind css npm package and create a tailwind config for you at ./tailwind.config.js.

In your tailwind.config.js file, add the following:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["**/*.razor", "**/*.cshtml", "**/*.html"],
  theme: {
    extend: {},
  },
  plugins: [],
}

This tells the Tailwind CLI to check any file in your solution with a .razor, .cshtml, or .html extension.

It does this so it knows what classes to include in your final built css file.

Create a main CSS file

Create a CSS file at Styles/input.css in your Blazor project. Then add the @tailwind directives.

@tailwind base;
@tailwind components;
@tailwind utilities;

Start the Tailwind CLI build process

Run the below command to start the Tailwind build process in your terminal.

npx tailwindcss -i ./src/input.css -o ./wwwroot/dist/output.css --watch

This command will search for css classes used in your project and then add them to the wwwroot/dist/output.css file.

This makes the final file size of your CSS file small and quick to download to the browser.

Reference CSS file in your _Layout

Finally, add a reference to the output.css file in your apps _Layout.cshtml file.

<!DOCTYPE html>
<html lang="en">
<head>
    ...
    <link href="~/dist/output.css" rel="stylesheet" />
    ...
</head>

Early Access

Dotnet Engine will be launching in early access soon. Signup with your email now to get notified when early access starts and a special launch price.