gpt4 book ai didi

css - 如何重置 CSS 变量(又名自定义属性)并使用后备变量?

转载 作者:技术小花猫 更新时间:2023-10-29 11:32:22 25 4
gpt4 key购买 nike

我正在尝试为盒子模型属性设置 CSS 变量。我想支持为各方和个别方面设定值(value)。我想有默认值,但无论哪种方式都可以覆盖。我尝试使用后备值,但收效甚微。

类似于:

:root {
--border-width-top: 0;
--border-width-right: 0;
--border-width-bottom: 0;
--border-width-left: 0;
--border-width: 0;
}
div {
border-color: red;
border-style: solid;
border-width: var(--border-width, var(--border-width-top) var(--border-width-right) var(--border-width-bottom) var(--border-width-left));
}


div {
--border-width-top: 10px;
}

这不会像 border-width 有默认值那样工作,然后它将始终优先于后备值。不确定目前是否有办法做到这一点,但我觉得很接近找到解决方案。

这是我正在玩的 stackblitz:stackblitz

最佳答案

您可以使用 initial 取消设置值以使用回退值:

:root {
--border-width-top: 2px;
--border-width-right: 2px;
--border-width-bottom: 2px;
--border-width-left: 2px;
--border-width: 0;
}
div {
margin:5px;
border-color: red;
border-style: solid;
border-width: var(--border-width, var(--border-width-top) var(--border-width-right) var(--border-width-bottom) var(--border-width-left));
}


div.box {
--border-width:initial;
--border-width-top: 10px;
}
<div>some content</div>
<div class="box">some content</div>

来自 the specification :

The initial value of a custom property is an empty value; that is, nothing at all. This initial value has a special interaction with the var() notation, which is explained in the section defining var().

To substitute a var() in a property’s value:

  1. If the custom property named by the first argument to the var() function is animation-tainted, and the var() function is being used in the animation property or one of its longhands, treat the custom property as having its initial value for the rest of this algorithm.
  2. If the value of the custom property named by the first argument to the var() function is anything but the initial value, replace the var() function by the value of the corresponding custom property. Otherwise,
  3. if the var() function has a fallback value as its second argument, replace the var() function by the fallback value. If there are any var() references in the fallback, substitute them as well.
  4. Otherwise, the property containing the var() function is invalid at computed-value time

关于css - 如何重置 CSS 变量(又名自定义属性)并使用后备变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com