Shinchan
Shinchan

Reputation: 113

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. On searching I have declared ViewEncapsulation.None in components, it worked well for one component and is still failing to apply for other components. Following is my angular.json file

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?

Any help is much appreciated!

Upvotes: 1

Views: 3743

Answers (1)

Remy
Remy

Reputation: 129

This might be the case because of CSS specificity.

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.

Explanation

To calculate the specificity of a CSS selector you start with 0 and add:

  • 1000 (for inline style attributes)
  • 100 (for each ID)
  • 10 (for each class, attribute, pseudo-class)
  • 1 (for each HTML element)

some examples:

button.class-1.class-2 has a specificity of 1 (1 html element) + 20 (2 classes) = 21

#myId.class-1 has a specificity of 100 (1 ID) + 10 (1 class) = 110

So the latter selector overwrites all CSS properties which are also declared in the first one.

For a complete explanation take a look at the corresponding site on w3schools.

Upvotes: 1

Related Questions