chh*_*vey 7 css inheritance css-variables
将自定义属性设置为 的值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>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
如何设置一个文字的值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>
Run Code Online (Sandbox Code Playgroud)
在此示例中,我希望第二个figcaption
(悬停时)继承其父级的红色边框,因此我设置--foobar
为inherit
. 但是,如示例 2 所示,这不会计算为inherit
,而是计算为从父属性继承的值--foobar
(如果有),在本例中为绿色。
我完全理解为什么 CSS 作者这样设计它:--foobar
就像任何其他 CSS 属性一样,所以设置inherit
应该继承它的值。所以我想我在问是否有一种解决方法可以让第二个figcaption
继承其父边界。
注意,我考虑过做
figure > figcaption:hover {
border: inherit;
}
Run Code Online (Sandbox Code Playgroud)
但这违背了使用 CSS 变量的目的。
如果有许多其他属性figure > figcaption
都使用 value var(--foobar)
,我不想为悬停场景重新定义它们。我宁愿只设置这些属性一次,然后根据上下文重新分配变量。
chh*_*vey -2
我做了一些思考,这个解决方案让我印象深刻。我可以将自定义属性与预处理器 mixins结合使用。
\n\n<style type="text/less">\n // NOTE: not syntactically valid CSS!\n .mx-border(@arg) {\n border: @arg;\n }\n figure {\n .mx-border(1px solid red);\n --foobar: 1px solid green;\n }\n figure > figcaption {\n .mx-border(var(--foobar));\n }\n figure > figcaption:hover {\n .mx-border(inherit);\n }\n</style>\n<figure>this figure has a red border\n <figcaption>this figcaption has a green border\n because it inherits --foobar</figcaption>\n</figure>\n<!-- on hover -->\n<figure>this figure has a red border\n <figcaption>This figcaption\n has a red border because the mixin\n sets the `border` property to `inherit`.</figcaption>\n</figure>\n
Run Code Online (Sandbox Code Playgroud)\n\n这样,我就可以将所有依赖的样式封装到.mx-border()
mixin 中。这样做不会利用 CSS 自定义属性,但它确实减轻了为:hover
.
本质上它与 write 相同,border: inherit;
只是增加了将更多样式放入 mixin 中而不必重复它们的能力。