Home > Software design >  Blazor C# - Using CSS isloation with code file behind component
Blazor C# - Using CSS isloation with code file behind component

Time:11-26

I have problems with getting a css file places behind a razor component to work

I have 3 files:

  • Index.razor
  • Index.razor.cs
  • Index.razor.css

but the css in the .css file is not used in the Index.razor page

Do I need to switch anything one or how do i make it work?

Indexfile content:

@page "/"

@namespace TestCSSIsolation.Pages

<h1>Hello, world!</h1>
<input value="@value" />
<button @onclick="@OnClick_Button">Click</button>

.cs file content:

namespace TestCSSIsolation.Pages;

public partial class Index
{
    private string value = string.Empty;
    private void OnClick_Button()
    {
        if (value.Trim().Length > 0)
        {
            value = string.Empty;
        }
        else
        {
            value = "Test";
        }
    }
}

.css file content:

body {
    border: solid 10px red;
}

button {
    background-color: pink;
}

input {
    background-color: lightblue;
}

Unfortunately I not allowed to post pictures here, but the result when I run the application is that the styling in the css file is not used on the component.

CodePudding user response:

It's working for me! output I was having trouble adding razor files to VS. Suggestion: Delete the file and add a new one. File structure

CodePudding user response:

Make sure that your _Host.cshtml has your CSS file included. To get scoped CSS working there should be a line like this:

<link href="[YOUR#_PROJECT_NAME].styles.css" rel="stylesheet" />

CodePudding user response:

I found another question that led me to a solution.

If I add this to my razor component then it works:

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

where "TestCSSIsolation" is my project name.

  • Related