【问题标题】:Force div children text color when specific class is specified指定特定类时强制 div 子文本颜色
【发布时间】: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&lt;div class="child blue"&gt;Child #2&lt;/div&gt; 保持蓝色。

问题是,如何在不为错误类指定.parent.error &gt; .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 &gt; .child.blue { color: blue; },它不会将 Child #2 的颜色更改为红色(至少在 Chrome 中不会)。只有当我添加了这种风格(我想避免).parent.error &gt; .child.blue { color: red !important; } 时它才有效。弗拉基米尔·哈拉(Vladimir Hala)的回答有效。

标签: html css


【解决方案1】:

没有更深入的头脑风暴,我的第一反应是: CSS 基本原则说 - 定义越接近,优先级越高。

因此,!important 部分是使事情正常运行所必需的。

或者,您可以将 CSS 定义重新考虑为相反的定义。 '.blue' 仅在父类不包含 .error时生效。

快速提示 - 对于非错误案例,类似这样:

.parent:not(.error) > .child.blue {
color: blue; 
}

【讨论】:

  • 感谢分享!它完美地工作。这是一个很好的妥协。谢谢你...
猜你喜欢
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 2020-06-29
  • 2015-10-10
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
相关资源
最近更新 更多