In Blazor, there are three ways to use different CSS files in different pages .
1. Use direct links of the CSS file via the <link> HTML element with its local or online reference in the href attribute.
<link href="StyleSheet.css" rel="stylesheet" />
2. Use inline <style></style> tag to define the custom styling for the page.
3. Include a new CSS file in the page by using a JavaScript interop in the OnInitialized method.
[script.js]
function includeCss(url) {
var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", url);
document.getElementsByTagName("head")[0].appendChild(element);
}
[Index.razor]
@page "/"
@inject IJSRuntime JSRuntime
<h1>Blazor Application</h1>
@code{
@code {
protected override async void OnInitialized ()
{
await JSRuntime.InvokeAsync<object>("includeCss");
}
}
Share with