html - 有趣的 CSS 行为 re : color inherit and currentColor

标签 html css css-selectors

假设我有以下 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 中确认。

Fiddle

* { 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 spana: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/

相关文章:

html - 为什么 Internet Explorer 以不同方式呈现输入?

HTML 无序列表 CSS

javascript - 获取html标签的大小

javascript - 我无法阻止 CSS 发光效果

gwt - 如何使 CSS "~"选择器在 GWT Css 资源中工作

javascript - 单击提交后,如何将 JS 函数中的数据插入表中?

javascript - 如何在 html 中对 &lt;style&gt; 声明进行沙箱处理?

html - 防止内部 div 扩展到超出固定高度的外部 div

css - 排除 CSS 中的第一个元素

html - 具有内联样式的 CSS 伪类