【发布时间】:2020-07-15 06:01:52
【问题描述】:
当其父级具有特定类时,我需要覆盖子级颜色。
.parent {
width: 100%;
}
.parent>.child {
color: black;
}
.parent>.child.blue {
color: blue;
}
.parent.error {
color: red !important;
}
.parent.error>.child {
color: red !important;
}
<div class="parent">
<div class="child">Child #1</div>
<div class="child blue">Child #2</div>
</div>
当使用 jquery $('.parent').addClass('error') 添加带有“错误”的父类时,只有 Child #1 颜色变为红色。 Child #2(在其班级中有额外的 blue)<div class="child blue">Child #2</div> 保持蓝色。
问题是,如何在不为错误类指定.parent.error > .child.blue 的情况下强制Child #2 将其颜色更改为红色。
/*If this style is added, it will work*/
.parent.error > .child.blue {
color: red !important;
}
谢谢...
【问题讨论】:
-
使用 jquery $('.parent').addClass('error') 添加父类时,只有 Child #1 颜色变为红色 --> 不,两者都会变成红色,所以不需要做任何事情
-
不幸的是,由于
.parent > .child.blue { color: blue; },它不会将 Child #2 的颜色更改为红色(至少在 Chrome 中不会)。只有当我添加了这种风格(我想避免).parent.error > .child.blue { color: red !important; }时它才有效。弗拉基米尔·哈拉(Vladimir Hala)的回答有效。