1

I need to know how it is established the precedence between ::ng-deep in angular. I have two different ::ng-deep from two different componets changing the css of the same element.

How can I give precedence to one of them? I would like to not use !important.

robe007
  • 3,523
  • 4
  • 33
  • 59
Davide
  • 185
  • 3
  • 22

2 Answers2

3

If you want to avoid using !important, it is best to implement it by Selector Specificity

Illustration

element   = 0, 0, 1
classes   = 0, 1, 0                 // Classes is larger than the element
id        = 1, 0, 0                 // ID has a higher specificity than classes

Example

<li class="item" id="active">...</li>
li { color: blue }               // Element: 0, 0, 1

.item { color: red; }            // Class: 0, 1, 0
                                 // Will override the color blue above

li.item { color: green; }        // 1 Element + 1 Class: 0, 1, 1
                                 // This will override the color red above

#active { color: pink; }         // ID: 1, 0, 0
                                 // Will override the color green above

li#active { color: violet; }     // 1 Element + 1 ID: 1, 0, 1
                                 // Will override the color pink above

li.item#active { color: brown }  // Element + Class + ID: 1, 1, 1
                                 // Will override the color violet above

You just need to count how many elements, classes or IDs being referenced in your css block and compare them by their specificity as per the illustration above

Have created a Stackblitz Demo for your reference. You can omit each block off css to check their specificity samples

NOTE:

  • This 1, 0, 0 (ID) is more higher than 0, 1, 3 (1 class + 3 elements) or any incremental values on those 2nd and 3rd
  • It's best to handle your elements with class to easily override styles out since ID has a higher specifity than classes but classes has higher specifity than elements so you can play easily between classes and elements
robe007
  • 3,523
  • 4
  • 33
  • 59
KShewengger
  • 7,853
  • 3
  • 24
  • 36
0

The answer is specificity. CSS specificity decides which style will be applied and get more precendence.

Make the one you want to apply more specific.

You can read about css specificity here :- https://www.w3schools.com/css/css_specificity.asp

Aakash Garg
  • 10,649
  • 2
  • 7
  • 25