【发布时间】:2020-12-29 13:16:32
【问题描述】:
我需要知道它是如何在角度中建立::ng-deep 之间的优先级的。我有两个不同的 ::ng-deep 来自两个不同的组件,它们更改了同一元素的 css。
我怎样才能优先考虑其中之一?我不想使用!important。
【问题讨论】:
-
为这个组件添加一些类并在你的样式中使用它,并尽量不要使用::ng-deep(很快它将从浏览器支持中删除)
我需要知道它是如何在角度中建立::ng-deep 之间的优先级的。我有两个不同的 ::ng-deep 来自两个不同的组件,它们更改了同一元素的 css。
我怎样才能优先考虑其中之一?我不想使用!important。
【问题讨论】:
如果要避免使用!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 的特异性高于elements,因此您可以轻松地在类和元素之间进行游戏李>
【讨论】:
答案是特异性。 CSS 特定性决定了将应用哪种样式并获得更多优先权。
让你想应用的那个更具体。
您可以在此处阅读有关 css 特异性的信息:- https://www.w3schools.com/css/css_specificity.asp
【讨论】: