css.net-8.0hosted-blazor-webassemblyasp.net-core-css-isolation

Blazor Web Assembly CSS isolation doesn't work


I migrated my Blazor WASM app to .NET 8, and I realised that CSS is not working if I use it in {component}.razor.css.

I mean

File Component.razor:

<div class="collapse navbar-collapse" id="navbarResponsive">
    <ul class="navbar-nav">
        <li class="nav-item"><a class="nav-link js-scroll-trigger" href="@AllResourcesResolver["navbar_inicio"]"> @AllResourcesResolver["navbar_inicio"] </a></li>
    </ul>
</div>

<style>
    .navbar-dark .navbar-nav .nav-link {
        color: white;
    }
</style>

This CSS works, but if I put the same CSS into {component}.razor.css, it doesn't work.

File Component.razor.css:

.navbar-dark .navbar-nav .nav-link {
    color: white;
}

Makes no sense to me, any help is welcome!


Solution

  • my first post ever. I hope it helps!

    I have a .NET 8 Blazor Web App (Server, Web Assembly, Auto). In my client project under the default Pages folder, I was running into the same issue as you when trying to apply CSS through a {Componenet}.razor.css file. I had set @rendermode InteractiveWebAssembly for this component page.

    I've run into issues with IntelliSense not activating on razor files before and that corrupting the build compilation. I found my solution for this CSS isolation issue there. I noticed in my new {Componenet}.razor.css file the IntelliSense feature was not present even after using 'Ctrl + Space'. Usually, I just delete the file and remake it a couple of times to get it to work. However, that did not work for me this time.

    My solution ended up being:

    1. Delete the {Componenet}.razor.css file.
    2. Run the application in Debug mode.
    3. Navigate to the {Component}.razor page.
    4. Add {Componenet}.razor.css in my Solution Explorer with its code.
    5. Click the Hot Reload button in Visual Studio.

    That's it. All of a sudden, my application is properly handling the CSS isolation in Blazor Web Assembly. I've even closed out Visual Studio entirely to verify that my solution persisted.