DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Sridhar Narasimhan
Sridhar Narasimhan

Posted on

.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 .NET 5.0 preview 8. Please join to check out the easy step by step process

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

Create Blazor webassembly appl

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

Create Razor class library

  • 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

Create scoped CSS for Blazor components

  • Add MyComponent project reference to Blazor client application.
  • Create a razor component in Blazor client application Cssisolation.razor
@page "/cssisolation"
<h3>Cssisolation</h3>
<Component1>
</Component1>
  • 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.

Browser dev tool to check strange identifiers

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

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.