css自定义属性是否有null或undefined或“falsy”值?

时间:2018-05-23 13:28:13

标签: css css-variables

我想创建一个组件并公开可以被父元素覆盖的某些属性。

这是一个例子。假设我正在创建一个具有自己颜色的按钮,但如果定义了--button-bg-color则允许更改其背景颜色:

.my-button {
  --bg-color: blue;

  /* lots of other css... */

  /**
    * here I assume that there might be a --button-bg-color defined,
    * but I have a fallback to my own --bg-color variable
    */
  background-color: var(--button-bg-color, var(--bg-color));
}

上面代码的问题是--button-bg-color变量在样式的深处被引用。

我希望我能做的就是在某个地方声明我可能想要使用这个变量。这将告诉我该组件预计会被覆盖。

也许是这样的?

.my-button {
  --button-bg-color: undefined; /* is there something like undefined? */
  --bg-color: blue;

  /* the rest of the code is the same */
}

1 个答案:

答案 0 :(得分:3)

哦,我刚刚意识到我们可以做到这一点:

.my-button {
  --bg-color: var(--button-bg-color, blue); /* inherit with fallback */

  /* lots of other css... */
  background-color: var(--bg-color);
}

这样也可以减少重复次数。