将自定义属性设置为 的值inherit完全符合您对每个其他 CSS 属性的期望:它继承其父级的相同属性值。
<style>
figure {
border: 1px solid red;
}
figure > figcaption {
border: inherit;
}
</style>
<figure>this figure has a red border
<figcaption>this figcaption has the same border
as its parent because it is inherited</figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)
<style>
figure {
--foobar: 1px solid green;
}
figure > figcaption {
--foobar: inherit;
border: var(--foobar);
}
</style>
<figure>this figure has no border
<figcaption>this figcaption has a green border
because it explicitly inherits --foobar</figcaption>
</figure>
Run Code Online (Sandbox Code Playgroud)
让我们考虑这个简化的示例,以说明问题:
: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);
}Run Code Online (Sandbox Code Playgroud)
<!-- 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 …Run Code Online (Sandbox Code Playgroud)