重置CSS样式中的颜色属性

8

能否用这种方式定义样式?在此示例中,类child通常为红色,除非它被包裹在parent类中,我希望它重置,以便使用parent的样式属性定义的颜色。

.child {
 color: red;
}

.parent > .child {
 color: _clear_;
}

<div class="parent" style="color:blue;">
 <div class="child">Some Text</div>
</div>
2个回答

18

我认为对于.parent > .childcolor: inherit; 是您要找的内容:

.child {
    color: red;
}

.parent > .child {
    color: inherit;
}
<div class="parent" style="color:blue;">
    <div class="child">This will be blue</div>
</div>

<br/>

<div class="child">This will still be red</div>

JSFiddle供示例参考


2

如果您正在使用有效的选择器,就像在您的示例中一样,您应该使用inherit

.child {
 color: red;
}

.parent > .child {
 color: inherit;
}

然而,如果你想要更复杂的东西,比如“基于父元素没有特定属性来设置子元素的样式”,那么纯CSS可能无法实现。此外,有些子元素可能无法从父元素逻辑地继承样式,因此请务必在可以从中继承子元素的父元素上设置“父元素”样式规则,并且你已经考虑到该规则(因此不要将其设置得太高,以至于你没有打算为该场景设置该颜色)。例如,在上面的示例中,如果父元素没有内联样式规则,则不会有color规则,因此子元素将从更高的位置获取值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接