【发布时间】:2015-10-26 00:11:34
【问题描述】:
我有一个 CSS 类“MyParent”,它被多个子类继承。 我想要“MyParent”类的一些属性,应该被子类覆盖,并且这个覆盖不应该影响其他子类。 请查找以下示例。
.MyParent {
border-style: solid;
border-color: red;
background-color: yellow;
color: red;
}
.MyChild1 .MyParent{
background-color: blue !important;
color: white !important;
}
.MyChild2 .MyParent{
background-color: yellow !important;
color: black !important;
}
我的 Html 如下所示。
<div class="MyParent">
this is parent div
</div>
<div class="MyChild1">
this is child1
</div>
<div class="MyChild2">
this is child2
</div>
我希望 MyParent div 以黄色背景颜色显示,字体颜色为红色,这工作正常,但尽管我覆盖了属性,但其余 div 没有按预期工作。我所做的是,请在下面找到代码。
.MyChild1, .MyParent{
background-color: blue !important;
color: white !important;
}
.MyChild2, .MyParent{
background-color: green !important;
color: white !important;
}
现在它部分工作,但我们在类“MyChild2”中覆盖的属性正在影响父类属性。因此,具有“MyParent”类的 div 由于这种继承而没有按预期进行渲染。因此,在应用程序的大多数地方,输出都受到干扰。如果我想让它按预期工作,我可以再写一个子类,我们可以做到,而且每次都写子类也很烦人一些属性,如边框颜色没有被继承 .但是为什么在 CSS 中会出现这种行为,以及我们如何纠正它。谁能给我解释一下。
提前致谢, 萨兰。
【问题讨论】: