假设我有以下 HTML:
<a id=link1><span>Link 1</span></a>
<a id=link2><span>Link 2</span></a>
以及以下 CSS:
a { color: white; }
a:hover { color: green; }
#link1 span { color: white; }
#link2 span { color: inherit; }
a:hover span { color: currentColor; }
有趣的是,悬停时,span
在链接 1 中将保持白色,因为它有 color: white
显式设置,而 span
在链接 2 中将变为绿色,就好像 color: inherit
不足以提供“当前颜色”。
换句话说,currentColor
似乎没有选择 inherit
指定的颜色.即使我将倒数第二行更改为更具体的内容,也会发生这种情况
#link2 span, #link2:hover span { color: inherit; }
问题:这是预期的行为,还是可以将其视为错误?已在 Firefox 和 Chrome 中确认。
* { font-family: 'trebuchet ms'; }
code { color: #c00; font-family: 'courier new'; font-size: .95em; }
a { display: block; color: white; background: black; padding: 1rem; margin: 1rem; cursor: pointer; text-align: center; }
a:hover { color: green; }
#link1 span { color: white; }
#link2 span { color: inherit; }
a:hover span { color: currentColor; }
<p>On hover to link 1, the <code>span</code> inside stays white because it has <code>color: white</code> explicitly set, and this is picked up as its <code>currentColor</code></p>
<a id=link1><span>link 1 (I stay white)</span></a>
<p>The <code>span</code> inside link 2, however, has <code>color: inherit</code> set, inheriting the parent <code>a</code>'s <code>color: white</code> definition. This, it seems, is insufficient for white to be picked up as its <code>currentColor</code> on hover to the <code>a</code>, and so it goes green due to the rule <code>a:hover { color: green; }</code>.</p>
<a id=link2><span>link 2 (I go green)</span></a>
最佳答案
If currentColor is used as the value of the color property, it instead takes its value from the inherited value of the color property. MDN
一方面我们有上述事实,但这里我们有 CSS specificity在玩:
#link1 span
和 #link2 span
比 a:hover span
具有更多特异性 - 所以值在此 CSS 规则中指定的优先。
这将继承 parent 的绿色颜色:
#link2 span {
color: inherit;
}
Inheritance is always from the parent element in the document tree, even when the parent element is not the containing block. MDN
这将设置白色颜色:
#link1 span {
color: white;
}
关于html - 有趣的 CSS 行为 re : color inherit and currentColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931290/