Before starting, ensure you have the following installed:
dotnet new mvc -n YourProjectName
cd YourProjectName
npm init -y
This creates a package.json
file.npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
This creates a tailwind.config.js
file.tailwind.config.js
file and update the content
property to include your Razor and CSHTML files:module.exports = {
content: [
'./Pages/**/*.cshtml',
'./Views/**/*.cshtml',
'./Views/Shared/**/*.cshtml'
],
theme: {
extend: {},
},
plugins: [],
}
wwwroot/css
folder, create a new file named site.css
(if it doesn’t already exist).site.css
:@tailwind base;
@tailwind components;
@tailwind utilities;
package.json
file and add a script to build Tailwind CSS:"scripts": {
"css:build": "npx tailwindcss -i ./wwwroot/css/site.css -o ./wwwroot/css/styles.css --minify"
}
This script:site.css
as the input.styles.css
..csproj
.csproj
file and add the following code to ensure Tailwind CSS is built when the project is compiled:<ItemGroup>
<UpToDateCheckBuilt Include="wwwroot/css/site.css" Set="Css" />
<UpToDateCheckBuilt Include="tailwind.config.js" Set="Css" />
</ItemGroup>
<Target Name="Tailwind" BeforeTargets="Build">
<Exec Command="npm run css:build"/>
</Target>
_Layout.cshtml
(located in Views/Shared
).<link rel="stylesheet" href="~/css/styles.css" asp-append-version="true" />
dotnet run
To automatically rebuild Tailwind CSS when changes are made, add a watch script to package.json
:
"scripts": {
"css:build": "npx tailwindcss -i ./wwwroot/css/site.css -o ./wwwroot/css/styles.css --minify",
"css:watch": "npx tailwindcss -i ./wwwroot/css/site.css -o ./wwwroot/css/styles.css --watch"
}
Run the watch script during development:
npm run css:watch
Your ASP.NET 7 MVC project is now set up with Tailwind CSS! You can start using Tailwind's utility classes to style your application.
For more details, refer to the official Tailwind CSS documentation and the ASP.NET MVC integration guide.