【发布时间】:2019-04-13 20:36:36
【问题描述】:
让我们考虑这个简化的例子来说明问题:
:root {
--color:rgba(20,20,20,0.5); /*defined as the default value*/
}
.box {
width:50px;
height:50px;
display:inline-block;
margin-right:30px;
border-radius:50%;
position:relative;
}
.red {background:rgba(255,0,0,0.5);}
.blue {background:rgba(0,255,0,0.5);}
.box:before{
content:"";
position:absolute;
top:0;left:0;right:0;bottom:0;
border-radius:50%;
transform:translateX(30px);
background:var(--color);
filter:invert(1);
}
<!-- we can add any color we want -->
<div class="box red" style="--color:rgba(0,255,0,0.5);">
</div>
<div class="box blue" style="--color:rgba(0,255,255,0.5);">
</div>
<!-- we can add the same color but this won't be dynamic -->
<div class="box red" style="--color:rgba(255,0,0,0.5);">
</div>
<!-- it would be good to be able to inherit the value but this won't work -->
<div class="box red" style="--color:inherit;">
</div>
在上面的代码中,我们可以使用 CSS 变量来操作伪元素的background。在某些情况下,我们需要与主元素具有相同的颜色,但由于我们不知道使用什么颜色,因此无法手动设置,最好的方法是使用 inherit 值。
正如这里解释的:Css display property set to inherit with variable doesn't work,inherit 的使用将不起作用。
有什么方法可以将 inherit 值存储在 CSS 变量中并稍后在任何属性中使用它(在我们的示例中为 background)?
【问题讨论】:
标签: css css-variables