将自定义属性设置为值inherit
完全符合您对其他所有 CSS 属性的期望:它继承其父级的相同属性值。
普通财产继承:
<style>
figure {
border: 1px solid red;
}
figure > figcaption {
border: inherit;
}
</style>
<figure>this figure has a red border
<figcaption>this figcaption has the same border
as its parent because it is inherited</figcaption>
</figure>
自定义属性继承(显式):
<style>
figure {
--foobar: 1px solid green;
}
figure > figcaption {
--foobar: inherit;
border: var(--foobar);
}
</style>
<figure>this figure has no border
<figcaption>this figcaption has a green border
because it explicitly inherits --foobar</figcaption>
</figure>
自定义属性继承(隐式):
所有自定义属性(不同于border
) 默认继承
<style>
figure {
--foobar: 1px solid green;
}
figure > figcaption {
border: var(--foobar);
}
</style>
<figure>this figure has no border
<figcaption>this figcaption has a green border
because it implicitly inherits --foobar</figcaption>
</figure>
我的问题
你如何设置literal的价值inherit
自定义属性,当您希望其值实际计算为关键字时inherit
?
<style>
figure {
border: 1px solid red;
--foobar: 1px solid green;
}
figure > figcaption {
border: var(--foobar);
}
figure > figcaption:hover {
--foobar: inherit;
}
</style>
<figure>this figure has a red border
<figcaption>this figcaption has a green border
because it inherits --foobar</figcaption>
</figure>
<!-- on hover -->
<figure>this figure has a red border
<figcaption>I want this figcaption
to have a red border (inherited from figure)
but its border is green!</figcaption>
</figure>
在这个例子中,我想要第二个figcaption
(悬停时)继承其父级的红色边框,所以我设置--foobar
to inherit
。然而,如示例 2 所示,这并不能计算为inherit
,它计算从父母的财产继承的值--foobar
(如果有),在本例中为绿色。
我完全理解CSS作者为什么这样设计:--foobar
就像任何其他 CSS 属性一样,因此设置inherit
应该继承它的价值。所以我想我是在问是否有解决方法来获得第二个figcaption
继承其父级的边界。
注意,我考虑过做
figure > figcaption:hover {
border: inherit;
}
但这违背了使用 CSS 变量的目的。
如果还有很多其他属性figure > figcaption
全部使用该值var(--foobar)
,我不想为悬停场景重新重新定义它们。我宁愿只设置这些属性一次,然后根据上下文重新分配变量。