1

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!

4
  • Try adding the !important keyword in your css and see if the styles are applied Commented Sep 29, 2020 at 17:29
  • @OwenKelvin yeah this worked but is it the recommended solution as we have to add !important to every style we write Commented Sep 29, 2020 at 17:38
  • You may have to. More specific css will always be applied unless you overide them with the !important keyword Commented Sep 29, 2020 at 17:44
  • @OwenKelvin yeah but that's not case when we are having the styles in component css file Commented Sep 29, 2020 at 17:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.