【发布时间】:2017-02-14 08:41:09
【问题描述】:
将自定义属性的值设置为 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>
我的问题
当您希望其值实际计算为关键字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 设置为inherit。但是,如示例 2 所示,这不会计算到 inherit,它会计算到从父属性 --foobar(如果有的话)继承的值,在本例中为绿色。
我完全理解 CSS 作者为什么这样设计它:--foobar 就像任何其他 CSS 属性一样,所以设置 inherit 应该继承它的值。所以我想我想问是否有解决方法让第二个figcaption 继承其父级的边界。
注意,我考虑过
figure > figcaption:hover {
border: inherit;
}
但这违背了使用 CSS 变量的目的。
如果figure > figcaption 中有许多其他属性都使用值var(--foobar),我不想为悬停场景重新定义它们。我宁愿只设置一次这些属性,然后根据上下文重新分配变量。
【问题讨论】:
-
--foobar不是属性...它是属性值。只能继承属性。 -
这样看...
--foobar: inherit;会编译成1px solid green: inherit这没有意义。 -
不管它们叫什么,您的演示都不会像您想象的那样工作。在第一个示例中, figcaption 有一个绿色边框,因为这是您告诉它的...而不是因为它是继承的。正如我所说的
1px solid green: inherit没有意义。 -
1px solid green: <anything>;没有意义,但--foobar: <anything>;仍然有效(无论<anything>是否为inherit)。我相信您没有正确区分--foobar(一个属性)和var(--foobar)(一个值)。您部分正确:在我的第二个(不是第一个)示例中,边框是绿色的,因为border: var(--foobar);计算为border: 1px solid green;。尽管border本身没有被继承也是正确的,但自定义属性--foobar是 继承的,它赋予了边框它的值。
标签: css inheritance css-variables