繁体   English   中英

为什么子组件样式被全局 css 覆盖?

[英]why child component styles overwriting by global css?

我正在我的 index.html 中导入一个基本的 css 文件,其中包含宽度为 auto,但这种样式优先于我使用 styleUrls: ["..."] 在组件中定义的样式(使用宽度为 70%)。 确保我的组件范围的 css 优先于传统方式定义的样式的最佳方法是什么? 我应该将全局样式范围限定在顶级组件吗?

一般来说,组件中的 css 是具有优先权的。 你可以尝试使用

encapsulation: 在你的 app.component 中的 ViewEncapsulation.None。

如果您的组件中有一个类,它将具有优先权。

https://angular.io/docs/ts/latest/guide/component-styles.html

您可以增加全局 css 中选择器的特异性。

当你在你的<my-comp class="some-class">

.someClass {
  width: 70%;
}

然后你可以覆盖

body .some-class.some-class {
  width: 100%;
}

body my-comp.some-class.some-class {
  width: 100%;
}

提高选择器特异性的方法最适合您取决于您​​的具体要求。

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

为了覆盖全局 scss,只需在component.ts文件中添加以下行(encapsulation: ViewEncapsulation.None)

  @Component({  selector: 'app-custom-component',
      templateUrl: './custom-component.component.html',
      styleUrls: ['./custom-component.component.scss'],
      encapsulation: ViewEncapsulation.None
    })

暂无
暂无

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

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