Unable to overwrite CSS variable with its own value

匆匆过客 提交于 2019-11-29 11:05:46

As commented above, CSS is not a programming language and you are having a cyclic dependency wanting to express a property with the same property which will not work.

Refering to the specification:

Custom properties are left almost entirely unevaluated, except that they allow and evaluate the var() function in their value. This can create cyclic dependencies where a custom property uses a var() referring to itself, or two or more custom properties each attempt to refer to each other.

A common fix to that situation is to add more variables to avoid any cyclic dependency.

:root {
  --bs:50px;
  --bl:16px;
  --box-size:var(--bs); 
  --box--larger:var(--bl);
}

.box {
  width: var(--box-size);
  height: var(--box-size);
  border: 1px solid red;
}

.box--larger {
  --box-size: 66px;
}

.box--larger1 {
  --box-size: calc(var(--bs) + var(--bl));
}

.box--larger2 {
  --box-size: calc(50px + var(--bl));
}
<div class="box">1</div>
<div class="box box--larger">2</div>
<div class="box box--larger1">3</div>
<div class="box box--larger2">4</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!