In a recent project, I needed to build something similar to a syntax highlighter for a Blazor application. The idea was to create a component that outputs a raw HTML fragment using <span class="style-1">text</span> elements to colorize parts of a string. It also needed to use CSS isolation, since the styles are specific to that component.
I have already written about these two topics independently. This post shows how to use them together!
I created a component named Highlighter.razor and its scoped CSS file Highlighter.razor.css:

The CSS is very simple:
CSS
.style-0 { background-color: darkgrey; }
.style-1 { background-color: orange; }
.style-2 { background-color: chartreuse; }
The component takes a string and wraps each character in a <span> with the class style-xxx from the CSS file:
Razor
@highlighted
@code {
MarkupString highlighted;
[Parameter]
public string Value { get; set; }
protected override void OnParametersSet()
{
var value = Value ?? "";
var htmlBuilder = new StringBuilder();
for (var i = 0; i < value.Length; i++)
{
htmlBuilder
.Append("<span class=style-").Append(i % 3).Append('>')
.Append(HtmlEncoder.Default.Encode(value[i].ToString()))
.Append("</span>");
}
highlighted = new MarkupString(htmlBuilder.ToString());
}
}
The component generates the correct HTML. However, the style is not applied:

CSS isolation occurs at build time. During this process, Blazor rewrites CSS selectors to match markup rendered by the component. In this case, the generated CSS file looks like:
CSS
.style-0[b-c2x6l882ml] { background-color: darkgrey; }
.style-1[b-c2x6l882ml] { background-color: orange; }
.style-2[b-c2x6l882ml] { background-color: chartreuse; }
To match the CSS selector, the span elements must have the attribute b-c2x6l882ml. This value is generated by Blazor at build time and is not accessible from code at runtime. Rather than hardcoding it in the component, you can set a fixed value by editing the csproj file:
csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Update="Pages/Highlighter.razor.css" CssScope="b-highlight" />
</ItemGroup>
</Project>
After rebuilding the project, the generated CSS file will contain the specified scope:
CSS
.style-0[b-highlight] { background-color: darkgrey; }
.style-1[b-highlight] { background-color: orange; }
.style-2[b-highlight] { background-color: chartreuse; }
You can now edit the component to add this attribute to the span elements:
Razor
...
for (var i = 0; i < value.Length; i++)
{
htmlBuilder
.Append("<span b-highlight class=style-").Append(i % 3).Append('>')
.Append(HtmlEncoder.Default.Encode(value[i].ToString()))
.Append("</span>");
}
...
Now the page renders as expected:

#Additional resources
Do you have a question or a suggestion about this post? Contact me!