Written by Mark Pringle | Last Updated on Wednesday, November 30, 2022

CSS ASP.NET Version: 6.0 Tutorial Articles

CSS isolation in ASP.NET Core 6.0 means you can define a Cascading Style Sheet specific to a page or view while overriding any global styles you may have created. It can be used in Razor and Blazor pages.

Using CSS isolation keeps global stylesheets from becoming monolithic while it minimizes the CSS footprint.

CSS isolation in ASP.NET Core 6.0 is not to be confused with the CSS isolation property used in the CSS language, which defines whether an element must create new stacking content.

Enabling CSS Isolation

To use CSS Isolation, follow this tutorial using the DemoProject we created or an MVC project of your own. In our tutorial, we will add CSS Isolation to the Privacy.cshtml view created by Visual Studio.

  1. Expand the views folder in your project. 
  2. Right-click on the folder that contains the view to which you want to add the CSS. In this scenario, it’s the Home folder since it houses our Privacy page.
  3. Add a new Class...

Add The CSS Isolation Class

The CSS Isolation class name must mirror the name of the view to which you apply it. In this case, we are applying the class to the Privacy.cshtml view, so we need to name the CSS Isolation file <ViewName>.cshtml.css. or Privacy.cshtml.css.

  1. Click Add.

Name the CSS Isolation Class

You will see that the newly created .css file has attached itself to the Privacy view automatically.

Privacy CSS

Before styles are added to the CSS Isolation class, the Privacy page Heading 1 is black.

Before the CSS Isolation Class is Used

Let's change the Heading 1 style to blue.

  1. Open the newly created .css file.
  2. Remove any code that is in the new Privacy.cshtml.css file.
  3. Add the following code to the .css file and save it.
h1 {
    color: blue;
}

After the CSS Isolation class is used, the Privacy page Heading 1 looks like this.

After the CSS Isolation Class is Used

That's it! You've added a CSS Isolation to the Privacy page.