Blazor CSS Isolation: Scoped Styles in .NET 5

A preview feature for .NET 5 (arriving Nov 2020) is CSS Isolation. Similar to Vue’s `scoped` styles or React Modules, this prevents style leakage between components.

How it Works

Create a file matching the component name: `Counter.razor.css`.

/* Counter.razor.css */
h1 { 
    color: red; 
}

At build time, Blazor rewrites HTML with a unique attribute `b-123abc` and rewrites CSS:

h1[b-123abc] {
    color: red;
}

The Deep Combinator

To style child components from a parent scope, use `::deep`.

.parent ::deep .child-element {
    border: 1px solid black;
}

Key Takeaways

  • No more BEM or global CSS conflicts.
  • Include the bundled CSS in `index.html`: `<link href=”MyApp.styles.css” rel=”stylesheet” />`.
  • Crucial for maintaining large apps.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.