Blazor CSS Isolation: Scoped Styles in .NET 5

.NET 5 brings CSS isolation to Blazor, a feature developers have been requesting since Blazor’s inception. If you’ve used Vue’s scoped styles or Angular’s component styles, you’ll feel right at home. CSS isolation ensures that styles defined for a component only apply to that component – no more worrying about global CSS conflicts.

How It Works

To use CSS isolation, create a CSS file with the same name as your component plus .css. Blazor’s build process automatically scopes these styles to your component using generated attributes.

Components/
├── Counter.razor
├── Counter.razor.css    ← Scoped styles for Counter
├── WeatherView.razor
└── WeatherView.razor.css

Example

/* Counter.razor.css */
h1 {
    color: #0066cc;
    font-size: 2rem;
}

.counter-button {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    cursor: pointer;
    transition: transform 0.2s;
}

.counter-button:hover {
    transform: scale(1.05);
}

At compile time, Blazor generates unique scope identifiers. The HTML becomes <h1 b-3xxtam6d07> and CSS becomes h1[b-3xxtam6d07]. This ensures styles only match elements in that specific component.

Styling Child Components

By default, scoped CSS doesn’t affect child components. Use the ::deep combinator to pierce the isolation boundary when needed:

/* Parent.razor.css */
::deep h1 {
    color: red;  /* Affects h1 in child components */
}

/* Only for direct children */
::deep > .child-class {
    margin: 1rem;
}

CSS Preprocessors

CSS isolation works with preprocessors. Name your file Component.razor.scss, configure your build to compile SCSS, and the output CSS file will be picked up by Blazor’s scoping mechanism.

Bundle Output

All isolated CSS is bundled into a single file: {ProjectName}.styles.css. Include this in your index.html or _Host.cshtml. The bundle is automatically linked in new .NET 5 Blazor templates.

Key Takeaways

  • CSS isolation scopes styles to individual components automatically
  • Create ComponentName.razor.css alongside your Razor file
  • Use ::deep to style child components when necessary
  • Works with CSS preprocessors like SCSS and LESS

References


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.