Search code examples
cssrazorblazor-server-side

Blazor Server Side formats MarkupString with embedded style while ignores Css file styles


My Blazor Server side application posts rich content obtained from a Web Api Core.
The content comes with arbitrary Html tags with a limited set of well known Css classes.
Blazor should style the content according to these classes, but it ignores the styles when declared in the matching css file.
However, it successfully formats the content if the style is embedded in the same razor page.

Following exercise demonstrates the problem.
Is there any workaround to keep the styles on the css file and have the markup content formatted accordingly?

The Test.razor page, with embedded style:

@page "/Test"

<div class="FromRazorStyle">
    Razor hard coded text, embedded razor style
</div>
<div class="FromCssFile">
    Razor hard coded text, style from Css file
</div>

@((MarkupString)FromRazorStyle)
@((MarkupString)FromCssFile)

<style scoped>
    .FromRazorStyle {
        font-weight:600;
        margin-bottom:20px;
    }
</style>

@code {
    string FromRazorStyle = "<div class='FromRazorStyle'>Markup string, embedded razor style<br/></div>";
    string FromCssFile = "<div class='FromCssFile'>Markup string, style from Css file<br/></div>";
}

The Test.razor.css file:

.FromCssFile {
    font-weight: 600;
    margin-bottom: 20px;
}

Result:
Razor hard coded text, embedded razor style
Razor hard coded text, style from Css file
Markup string, embedded razor style

Markup string, style from Css file


Solution

  • Yes, this is possible, but not necessarily easy! The problem is that the CSS isolation process rewrites the selectors in .razor.css files to include a randomly generated unique identifier. So, the CSS in your example actually becomes something like .FromCssFile[b-c2x6l882ml]. This identifier is also added as an attribute to all HTML tags present in the .razor file, but not to those in the markup string.

    One workaround is to manually set this CssScope identifier in the project file, as explained on this page, and then also insert it into the markup content tags.

    However, a simpler way in this case is probably to just put your current CSS in a static file, such as the default css/site.css, like this:

    .FromCssFile * {
        font-weight: 600;
        margin-bottom: 20px;
    }