.NET 5.0 Blazor bites - CSS isolation for Blazor components

.NET 5.0 Blazor bites - CSS isolation for Blazor components

In this blog, we are going to walk through on how the CSS isolation for Blazor components can be done in .NET 5.0 preview 8. Please join to check out the easy step by step process.

  1. Create a Blazor Webassembly application by enabling the ASP.NET core hosted option.
Blazor Webassembly creation

2. Add a new project (Razor class library) MyComponent to the solution.

Image for post

3. In the created razor class library you will have styles.css in the wwwroot folder. You can delete it and create your component scoped CSS files by creating a new file next to your component with .css extension. Scoped styles are available under _framework/scoped.styles.css

Image for post

4. Add MyComponent project reference to Blazor client application.

5. Create a razor component in Blazor client application Cssisolation.razor

@page “/cssisolation”


6. Build your application and you can check in your browser dev tools to view your newly scoped CSS classes applied to your components. Your HTML elements will have strange identifiers.

Scoped CSS for Blazor component

I hope you understood how Scoped CSS for Blazor components can be achieved. I have attached the sample link https://github.com/Sridhar-Narasimhan/Blazor-css-isolation for your reference