Course contentsShow
← C#
Lesson 1331 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Component Scoping and Encapsulation

Create style isolation by bundling CSS with individual components.

In this lesson, you will learn how to achieve style isolation in Blazor by bundling CSS files directly with your components to prevent unintended global style leaks.

The Problem of Global Styles

In traditional web development, CSS is often global. If you define a class named .button in a site-wide stylesheet, it applies to every element with that class across your entire application. As your project grows, this leads to "CSS bloat" and "style collisions," where changing a style for one component accidentally breaks the layout of another.

CSS Isolation in Blazor

Blazor provides a built-in mechanism to scope styles to a specific component. When you create a component—for example, ProfileCard.razor—you can create a companion file named ProfileCard.razor.css.

By placing your CSS in this specific file, Blazor’s build process automatically transforms the selectors. It appends a unique scope identifier to your CSS classes, like [b-xyz123].

For example, if your ProfileCard.razor.css contains:

.card {
    border: 1px solid blue;
    padding: 10px;
}

Blazor renders the HTML as:

<div class="card" b-xyz123>
    <!-- Content -->
</div>

And the CSS becomes:

.card[b-xyz123] {
    border: 1px solid blue;
    padding: 10px;
}

Why This Matters

Because the generated CSS is now tied to a unique attribute, your .card class will only affect the ProfileCard component. You are free to name your classes whatever you want (e.g., .container, .header, .footer) without worrying that another developer—or your future self—will inadvertently override those styles elsewhere in the application.

This encapsulation allows you to build modular, self-contained components that can be dropped into any part of your UI without causing "side effects" in your layout. It turns CSS from a source of global anxiety into a predictable, localized tool for design.

Key Takeaway: CSS isolation ensures that styles are bundled with their associated component, automatically scoping your CSS to prevent global conflicts and keep your UI code modular.