简体   繁体   English

Angular 全局 css 文件 css 不适用于其他组件

[英]Angular global css file css are not applying to other components

I am using Angular v10, I have a few CSS which are used across the application, so I have written that in our global styles.css file, but the CSS isn't applying to other components, if I write the same CSS in component related CSS it's working fine.我正在使用 Angular v10,我有一些 CSS 用于整个应用程序,所以我已经在我们的全局 style.css 文件中编写了它,但是如果我在组件中编写相同的 CSS,那么 CSS 不适用于其他组件相关的 CSS 它工作正常。 On searching I have declared ViewEncapsulation.None in components, it worked well for one component and is still failing to apply for other components.在搜索时,我在组件中声明了 ViewEncapsulation.None,它适用于一个组件,但仍然无法申请其他组件。 Following is my angular.json file以下是我的 angular.json 文件

angular.json angular.json

I have never faced this problem with any of the angular projects, is it any issue with the new versions of Angular or is it me doing anything wrong?我从来没有在任何 angular 项目中遇到过这个问题,是新版本的 Angular 有问题还是我做错了什么?

Any help is much appreciated!任何帮助深表感谢!

This might be the case because of CSS specificity.这可能是因为 CSS 的特殊性。

Simply put: different selectors have different specificity.简单地说:不同的选择器具有不同的特异性。 For example:例如:

If you have the following class declared in your global stylesheet:如果您在全局样式表中声明了以下类:

.some-class {
  color: red;
}

and in a component you have the following:在一个组件中,您有以下内容:

button.some-class {
  color: blue;
}

then the property color gets overriden with "blue" because the specificty of the CSS-selectors in the component is higher than in your global stylsheet.然后属性颜色被“蓝色”覆盖,因为组件中 CSS 选择器的特性高于全局样式表中的特性。

Explanation解释

To calculate the specificity of a CSS selector you start with 0 and add:要计算 CSS 选择器的特殊性,您可以从 0 开始并添加:

  • 1000 (for inline style attributes) 1000(用于内联样式属性)
  • 100 (for each ID) 100(每个ID)
  • 10 (for each class, attribute, pseudo-class) 10 个(对于每个类、属性、伪类)
  • 1 (for each HTML element) 1(对于每个 HTML 元素)

some examples:一些例子:

button.class-1.class-2 has a specificity of 1 (1 html element) + 20 (2 classes) = 21 button.class-1.class-2的特异性为 1(1 个 html 元素)+ 20(2 个类)= 21

#myId.class-1 has a specificity of 100 (1 ID) + 10 (1 class) = 110 #myId.class-1的特异性为 100 (1 ID) + 10 (1 class) = 110

So the latter selector overwrites all CSS properties which are also declared in the first one.所以后一个选择器会覆盖所有也在第一个选择器中声明的 CSS 属性。

For a complete explanation take a look at the corresponding site on w3schools .有关完整说明,请查看w3schools上的相应站点。

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

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