Search code examples
cssrazor

In Razor, problem with Html.Raw() when given an element having a class


In a Razor project I have

@{
    string elem="<span class=\"spec\">comment</span>";
}
<div>@Html.Raw(elem)</div>

and

.spec{
    color: red;
}

The color is not applied. Looking in the browser, in debugger, I noticed that I have to write

string elem="<span b-skxp0olev1 class=\"spec\">comment</span>";

And it works! If I look in the Styles tab, when I apply the magic word I see on top a styling entry like:

.spec[b-skxp0olev1] {
    color: red;
}

As a matter fact, I came with the described solution observing other elements in the Elements tab of Chrome debugger. For example, I have in my page something as simple as

<h6>Version</h6>

but I see in the Elements tab something like

<h6 b-skxp0olev1>Version</h6>

It looks that for most elements, maybe for all, that magic string is automatically added but not in case of Html.Raw() usage.

Another observation: I can write

string elem = "<span style=\"font-weight:bold\" class=\"spec\">comment</span>";

and the font is bolded even though the magic word is not added by me or by browser. So the problem is with classes and Html.Raw(). When I look in the Styles tab, I see the font-weight but not the spec class.

Analyzing the rest of the elements I see that there are two or three magic words used. Some of the elements use a magic word, other elements some other.

Of course, I don't want to always guess an use such b-skxp0olev1 magic. What to do?


Solution

  • I learned that the magic string is the result of a feature called css isolation available in Blazor but now, as it seems, introduced also in Razor. If you use a Visual Studio AspNetCoreMVC project sample this feature is enabled by default. I have also learned that, indeed, @Html.Raw() has a problem with this feature.

    The good news is that the magic word can be customized in csproj file.

    ASP.NET Core Blazor CSS isolation - Customize scope identifier format