【问题标题】:How to use CSS Variables only when they exist?如何仅在 CSS 变量存在时使用它们?
【发布时间】:2019-09-07 21:23:47
【问题描述】:

我有一些 CSS,我想要一个默认颜色,然后用一个变量覆盖它。当 CSS 变量不存在时,我想使用后备颜色。

:root {
    /*--tintColor: red;*/
}

.text {
    color: blue;
    color: var(--tintColor);
}

当变量未设置时,如果它被注释掉,颜色变为黑色。在这种情况下,我希望在未定义变量时颜色回落到蓝色。这可能吗?

【问题讨论】:

  • RTM - var(--tintColor, blue)
  • 太棒了! ^ 从来没有真正检查过文档,只是一直在使用 SASS,但这很可爱

标签: html css css-variables


【解决方案1】:

您可以指定fallback 属性,如var(--tintColor, blue) - 请参见下面的演示:

.text {
    color: blue;
    color: var(--tintColor, blue);
}
<div class="text">some text here</div>
<div class="text" style="--tintColor: red">some text here</div>

【讨论】:

  • 这条线 color: blue; 在 2k20:3 中是多余的
猜你喜欢
  • 2012-10-09
  • 2012-09-18
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
  • 2021-02-28
  • 2023-04-06
相关资源
最近更新 更多