Angular 来自不同组件的同一元素上的两个 ng-deep

Angular two ng-deep on the same element from different components

我需要知道 ::ng-deep 和 angular 之间的优先级是如何确定的。我有两个不同的 ::ng-deep 来自两个不同的组件,改变了同一元素的 css。

我怎样才能优先考虑其中之一?我不想使用 !important.

答案是特异性的。 CSS 特异性决定了将应用哪种样式并获得更高的优先级。

让你想要应用的那个更具体。

您可以在此处了解 css 特异性:- https://www.w3schools.com/css/css_specificity.asp

如果想避免使用!important,最好通过Selector Specificity

来实现

插图

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

例子

<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

您只需要计算在您的 css 块中引用了多少元素、类 或 ID,然后根据上图的具体情况比较它们

创建了一个Stackblitz Demo供大家参考。您可以省略每个块 css 以检查其特异性样本

注意:

  • 这个 1, 0, 0 (ID)0, 1, 3 (1 class + 3 elements) 或第二个和第三个
  • 的任何增量值更高
  • 最好用 class 处理元素,以便轻松覆盖样式,因为 ID 比 类 具有更高的特异性,但 classes 比 [=] 具有更高的特异性19=] 所以你可以在 类 和 elements
  • 之间轻松玩耍