简体   繁体   English

Blazor C# - 使用 CSS 隔离与组件后面的代码文件

[英]Blazor C# - Using CSS isloation with code file behind component

I have problems with getting a css file places behind a razor component to work我在将 css 文件放置在 razor 组件后面时遇到问题

I have 3 files:我有 3 个文件:

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

but the css in the.css file is not used in the Index.razor page但是.css文件中的css并没有在Index.razor页面中使用

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: .cs 文件内容:

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: .css 文件内容:

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.不幸的是我不允许在这里发布图片,但是当我运行应用程序时的结果是组件上没有使用 css 文件中的样式。

It's working for me!它为我工作! 输出 I was having trouble adding razor files to VS.我在将 razor 文件添加到 VS 时遇到了问题。 Suggestion: Delete the file and add a new one.建议:删除该文件并添加一个新文件。 文件结构

Make sure that your _Host.cshtml has your CSS file included.确保您的_Host.cshtml包含您的 CSS 文件。 To get scoped CSS working there should be a line like this:要使范围 CSS 工作,应该有这样一行:

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

I found another question that led me to a solution.我发现了另一个问题,使我找到了解决方案。

If I add this to my razor component then it works:如果我将它添加到我的 razor 组件中,它就会工作:

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

where "TestCSSIsolation" is my project name.其中“TestCSSIsolation”是我的项目名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM