css - css 自定义属性是否存在空值、未定义或“虚假”值?
问题描述
我想创建一个组件并公开某些可能被父元素覆盖的属性。
这是一个例子。假设我正在创建一个具有自己颜色的按钮,但如果有--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 */
}
解决方案
哦,好吧,我刚刚意识到我们可以这样做:
.my-button {
--bg-color: var(--button-bg-color, blue); /* inherit with fallback */
/* lots of other css... */
background-color: var(--bg-color);
}
这样重复的次数也更少。
推荐阅读
- c - setbuf 只影响stdio调用,不影响系统调用?
- javascript - 在 React Native 中迭代 for 循环时,如何在状态对象中添加键值对?
- vba - Word 宏:如何在表格排序中排除总行并摆脱错误 5992
- azure-cognitive-search - Azure 搜索在邻近搜索中返回额外的命中亮点
- python - 如何在噪声中添加非零元素?
- javascript - 如何从期权中获得价值?
- sql - 如何重用未创建的索引空间
- c++ - 如何在模板参数中调用成员?
- http - 渐进式 Web 应用程序可以与本地网络上的设备一起使用吗?
- java - 如何检查一个数组是否包含相同的值?