声明变量(如果尚未定义)



我有一个项目,它被拆分为父应用程序,并在单独的存储库中有几个可重用的子组件。 我想在这些子组件中定义默认的 CSS 变量,这些变量可以被父应用程序覆盖,但我找不到正确的语法。 这是我尝试过的:

/* parent */
:root {
--color: blue;
}
/* child */
:root {
--color: var(--color, green);
}
.test {
width: 200px;
height: 200px;
background: var(--color, red);
}

https://codepen.io/daviestar/pen/brModx

颜色应该是蓝色,但是当定义子:root时,颜色实际上是红色,至少在 Chrome 中是这样。

有正确的方法吗? 在 SASS 中,您可以向子变量添加一个!default标志,这基本上意味着"如果尚未声明,则声明"。

CSS 代表cascading style sheets, 所以你不能覆盖父母的任何内容......

唯一的方法是创建一个更强大的规则

看看.c1.p1

.parent {
--background: red;
}
.child {
--size: 30px;
--background: green; /* this wins */
background-color: var(--background);
width: var(--size);
height: var(--size);
}
.p1 .c1 {
--background: red; /* this wins */
}
.c1 {
--size: 30px;
--background: green;
background-color: var(--background);
width: var(--size);
height: var(--size);
}
<div class="parent">
<div class="child"></div>  
</div>
<hr />
<div class="p1">
<div class="c1"></div>  
</div>

感谢@Hitmands提示,我有一个简洁的解决方案:

/* parent */
html:root { /* <--- be more specific than :root in your parent app */
--color: blue;
}
/* child */
:root {
--color: green;
}
.test {
width: 200px;
height: 200px;
background: var(--color);
}

我会建议一种方法,方法是使组件中的变量别名并使用"父"或根变量作为主值,而局部值是!default

.parent {
--background: red;
}
.child {
--child_size: var(--size, 30px); /* !default with alias */
--child_background: var(--background, green); /* !default with alias */
background-color: var(--child_background);
width: var(--child_size);
height: var(--child_size);
}
<div class="parent">
<div class="child"></div>  
</div>
<hr>
<div class="child"></div>

相关内容

最新更新