Overview

CSS can be isolated to individual pages, views, and Components.

CSS isolation occurs at build time. Blazor rewrites CSS selectors to match the markup rendered by the Component. These rewritten CSS styles are then bundled as a static asset.

Isolate CSS for a Component

To enable Component-level isolation, create a .razor.css file matching the name of the .razor file of the Component in the same folder.

Isolate CSS for a Child Component

Use the ::deep pseudo-element to any descendant elements in the parent Component’s .razor.css file.

Example

Pages/Parent.razor

@page "/parent"

<div>
    <h1>Parent component</h1>

    <Child />
</div>

Shared/Child.razor

<h1>Child Component</h1>

Pages/Parent.razor.css

/* Declares that the h1 style declaration will apply to the parent Component and its children: */
::deep h1 { 
    color: red;
}

Important notes

  • Removing the <div> element removes the parent-descendant relationship. This would prevent the <h1> element in the Child from inheriting the style declaration.
  • Scoping:
    • When defining a CSS rule in a scoped CSS file, the scope is applied to the right-most element by default:
      • div > a is transformed to div > a[b-{STRING}] where {STRING} is a placehodler generated by the framework.
    • By using ::deep you can apply the rule to a different selector:
      • div ::deep > a is transformed to div[b-{STRING}] > a.
  • Scoped CSS only applies to HTML elements (not to Razor Components or Tag Helpers).

CSS Preprocessors (Sass, Less, etc)

CSS isolation does not natively support CSS preprocessors. However, CSS preprocessors can be integrated as long as preprocessor compilation occurs before Blazor rewrites the CSS selectors during the build process (which is when CSS isolation occurs). To do this in Visual Studio, configure existing preprocessor compilation as a Before Build task.

Also, AspNetCore.SassCompiler can compile SASS/SCSS files before CSS isolation occurs.

CSS isolation configuration

Razor Class Library (RCL) Support