【问题标题】:why child component styles overwriting by global css?为什么子组件样式被全局 css 覆盖?
【发布时间】:2017-03-02 14:17:31
【问题描述】:

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

【问题讨论】:

  • 请分享您的代码。

标签: css angular


【解决方案1】:

通常,组件中的 css 是具有优先权的。你可以尝试使用

封装:在你的 app.component 中查看Encapsulation.None。

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

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

【讨论】:

    【解决方案2】:

    您可以在全局 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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 2022-01-21
        • 1970-01-01
        • 2019-05-21
        • 1970-01-01
        • 2020-10-11
        相关资源
        最近更新 更多