Blazor 引入CSS

在Blazor中,引入CSS样式表有多种方式,下面是一些常用的方法:

直接在HTML中引入

wwwroot/index.html(对于Blazor WebAssembly应用程序)或Components/App.razor(对于Blazor Server应用程序)文件的部分直接引入CSS文件:

<head>  
    <!-- 其他头部内容 -->  
    <link href="css/your-styles.css" rel="stylesheet" />  
</head>

确保你的CSS文件放置在wwwroot/css/目录下(或任何你选择的静态文件目录),并且路径是正确的。

使用组件级别的CSS

你可以在组件的Razor文件中使用<style>标签来引入内联CSS样式,这对于组件级别的样式非常有用:

@page "/your-page"  
  
<h1>Your Page Title</h1>  
  
<style>  
    h1 {  
        color: blue;  
    }  
</style>

示例代码

CustomDialog.razor

使用CSS隔离(Scoped CSS)

Blazor 支持CSS隔离,它允许你为每个组件创建私有的CSS样式,这些样式只应用于该组件,而不会影响到其他组件。这是通过在组件的Razor文件旁边创建一个.razor.css文件来实现的。

例如,对于MyComponent.razor,你可以创建一个MyComponent.razor.css文件,并将该组件的样式放在其中。Blazor会自动处理这些文件的隔离。

/* MyComponent.razor.css */  
h2 {  
    color: green;  
}
<!-- MyComponent.razor -->  
@page "/my-component"  
  
<h2>My Component Title</h2>  
  
<!-- 其他组件内容 -->

示例代码

Modal.razor
Modal.razor.css

为特定组件创建CSS

在项目的wwwroot/css目录下(或者任何你选择的静态文件目录),为特定的组件创建一个CSS文件。例如,如果你有一个名为MyComponent.razor的组件,你可以创建一个MyComponent.css的CSS文件。
在MyComponent.css文件中编写该组件的样式:

/* MyComponent.css */  
.my-component-class {  
    background-color: lightblue;  
    padding: 10px;  
}

在MyComponent.razor文件的顶部,使用<link>标签来引用MyComponent.css文件。确保路径是正确的。

<!-- 引入CSS文件 -->  
<link href="css/MyComponent.css" rel="stylesheet" />  

示例代码

CustomDialog2.css
CustomDialog2.razor

posted @ 2023-07-16 12:56  Lulus  阅读(1330)  评论(0编辑  收藏  举报