是否有可能有一个基本上"撤消"先前规则的CSS规则?
一个例子:
<blockquote>
some text <em>more text</em> other text
</blockquote>
Run Code Online (Sandbox Code Playgroud)
让我们说这是这个CSS:
blockquote {
color: red;
}
Run Code Online (Sandbox Code Playgroud)
...但我希望<em>保持正常的文字颜色(你可能不一定知道).
基本上,有没有办法做这样的事情?
blockquote em {
color: inherit-from-blockquote's-parent
}
Run Code Online (Sandbox Code Playgroud)
编辑:实际上,我试图让这个工作中的代码实际上是一个比较复杂一点.也许这会更好地解释它:
This text should be *some unknown colour*
<ul>
<li>This text should be BLUE
<ul>
<li>Same as outside the UL</li>
<li>Same as outside the UL</li>
</ul>
</li>
</ul>
ul {
color: blue;
}
ul ul {
color: ???;
}
Run Code Online (Sandbox Code Playgroud)
仅使用CSS,您无法引用父母的父级.
您可以做的是尝试混合使用特定的CSS选择器和标记,以便显示所需的效果.
<td>
This is the enclosing element.
<ul>
<li>This is the first level UL, direct child of TD
<ul>
<li>This is the second level UL</li>
<li>Same as outside the UL</li>
</ul>
</li>
</ul>
</td>
Run Code Online (Sandbox Code Playgroud)
CSS:
td > ul
color: blue; /* this affects the "direct child" UL only */
}
Run Code Online (Sandbox Code Playgroud)
您可以将样式继承的深度限制为一个级别,因此内部UL在颜色方面没有样式,并从封闭文本中获取其设置.
阅读有关CSS子选择器的更多信息,并注意旧版浏览器可能有它们的怪癖.
编辑
对于Internet Explorer 6,子选择器可以在某种程度上伪造.使用前请务必系好安全带(条件评论等):
td ul {
color: expression(/TD/.test(this.parentNode.tagName)? "blue" : "black");
}
Run Code Online (Sandbox Code Playgroud)
这假定为"黑色"作为外部颜色.如果这个颜色值可能会发生变化,那我就不幸了.除非您可以定义expression()能够从上下文中获取颜色值(例如,检查父元素的其他属性).或者你放弃并使用JS框架,正如其他人已经建议的那样.
无需使用JS的懦弱解决方案当然是:
td ul.first {
color: blue;
}
Run Code Online (Sandbox Code Playgroud)
但我明白为什么你要避免这种情况.
使用此选项可确保继承覆盖可能设置颜色的其他内容:
blockquote em {
color: inherit !important;
}
Run Code Online (Sandbox Code Playgroud)