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

Swe*_*tha 7 css angular

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

Ron*_*nio 7

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

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

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

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


Roh*_*eja 6

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

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


Gün*_*uer 5

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

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

.someClass {
  width: 70%;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以覆盖

body .some-class.some-class {
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

或者

body my-comp.some-class.some-class {
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

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

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