Why Blazor CSS isolation not adding the link tag to load the bundled css file?

Viewed 5874

I created a Blazor component and an accompanying css file for the css isolation functionality in the WASM project. When the page is rendered, my element is not getting the css style defined in the css file. Upon inspecting the element, I can see the extra b-* attribute applied to it. I can see a MyProject.Client.styles.css file with the extra b-* added in the css file under ...\obj\Debug\net5.0\scopedcss\bundle\MyProject.Client.styles.css. (* is some random characters)

However, I expected that the Blazor build would add a link tag in the Head section so the browser loads this new bundled css file but it's not there. I used Fiddler and verified that no *.styles.css is being loaded by the browser, which is the problem. Already cleared the cache and application.

Am I missing some manual step or a setting for css isolation to add the link tag? I am using .NET 5.0 release version.

2 Answers

You have to add the tag for the bundled CSS file manually to the host page. Blazor does not add this for you.

<link href="MyProjectName.styles.css" rel="stylesheet">

I was facing very similar problem in my Blazor Server project based on .NET 6 where I leveraged the MudBlazor component library. I had to dive a little deeper than the accepted answer.

One of my pages required some tweaks for conditional background colors in a table and I was not able to have my classes from the isolated CSS file applied. After few hours of research on the internet and experimenting with shifting my custom CSS classes from the isolated CSS file to wwwroot\css\styles.css in my project folder structure and various placements of the stylesheet link for CSS isolation

<link href="<MyAssemblyName>.styles.css" rel="stylesheet"/>

it turned out that the CSS isolation applies only to plain HTML, not to Razor components, tag helpers etc. As stated in the MSDN documentation:

Important: Scoped CSS only applies to HTML elements and not to Razor components or Tag Helpers, including elements with a Tag Helper applied, such as <input asp-for="..." />.

The MudBlazor components surely are Razor components and therefore the scoped CSS feature is not supported. I had to keep my custom CSS classes in the wwwroot\css\styles.css stylesheet. With that I was able to achieve the look I needed on my pages/components.

In case you really need your scoped CSS applied you may try the workaround with the ::deep described here.

Related