gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:39:18 25 4
gpt4 key购买 nike

假设我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com