如何将 `inherit` 的值设置为 CSS 自定义 属性?

How do I set a value of `inherit` to a CSS custom property?

将自定义 属性 设置为 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)的情况下,我不想为悬停场景重新定义它们。我宁愿只设置这些属性一次,然后根据上下文重新分配变量。

我做了一些思考,这个解决方案让我大吃一惊。我可以将自定义属性与 preprocessor mixins.

结合使用
<style type="text/less">
  // NOTE: not syntactically valid CSS!
  .mx-border(@arg) {
    border: @arg;
  }
  figure {
    .mx-border(1px solid red);
    --foobar: 1px solid green;
  }
  figure > figcaption {
    .mx-border(var(--foobar));
  }
  figure > figcaption:hover {
    .mx-border(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>This figcaption
    has a red border because the mixin
   sets the `border` property to `inherit`.</figcaption>
</figure>

这样我就可以把所有的依赖样式都封装到.mx-border()mixin中了。这样做不会利用 CSS 自定义属性,但它确实减轻了为 :hover.

再次编写所有内容的麻烦

本质上,它与写作border: inherit;相同,只是增加了将更多样式放入mixin中的能力,而不必复制它们。