How to Handle CSS in Your .NET Application

1. Separate your CSS and HTML

CSS code belongs in stylesheets, and not in your views, pages or components.

Centralizing your CSS has the following advantages:

2. How do you add CSS files to your .NET application?

  1. Put the CSS files (along with your other static files) in the wwwroot folder of the application.

data/admin/2021/2/wwwroot.png

<head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title>@ViewData["Title"] - WebApplication1</title>
     <link rel="stylesheet" href="~/css/site.css" />
</head>
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
   {
      app.UseDeveloperExceptionPage();
   }
   else
   {
      app.UseExceptionHandler("/Error");
      // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
      app.UseHsts();
   }

  app.UseHttpsRedirection();
  app.UseStaticFiles();

  app.UseRouting();

  app.UseAuthorization();

  app.UseEndpoints(endpoints =>
  {
    endpoints.MapRazorPages();
  });
}

How to Use SASS in Your .NET Application

I’m a fan of using SASS.

What is Sass? SASS (Syntactically Awesome Stylesheets) is a CSS pre-processor that lets you incorporate features from programming languages into your app such as variables, mathematical operations, mixins, loops, functions, imports and other powerful features that can make using CSS much more powerful.

In order to use SASS, you write your CSS using the SCSS syntax. SASS then compiles your code, generating it into CSS.

I keep a separate SCSS folder in wwwroot to store the Sass files.

data/admin/2021/2/scss-to-css.png

When using SASS to typically use a task runner like Grunt to automatically generate your target CSS file when changes are made in your SCSS files. I generate the target directly in the CSS folder of wwwroot.