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

标签 css css-variables

我正在尝试为盒子模型属性设置 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/

相关文章:

android - 如何在 Android style.xml 文件中使用自定义父级?

css - 如何使用 CSS 将表格外的文本左对齐

javascript - 使用鼠标滚轮移动图像

HTML 到 PDF 转换。固定页脚在页面底部

css - 如何根据 CSS 变量值显示可变数量的元素

css - 无法让 CSS 变量在任何浏览器中工作

html - 导航标签显示布局

css - 从 JSON 文件或 typescript 文件定义 CSS 变量的方法?

css - 在 css 变量的 rgba 上设置不透明度/alpha

javascript - 如何从 HTMLLinkElement 获取 CSSStyleSheet