Can a recursive variable be expressed in css?

吃可爱长大的小学妹 提交于 2019-11-30 18:59:33
Temani Afif

You can use two CSS variables to simulate the recursive behavior and avoid cycle dependency.

Here is an example:

body {
  --x: 10;
}
.y {
  --y: calc(var(--x) + 1);
}
.x{
  --x: calc(var(--y) + 1);
}
.result {
  border-right:calc(1px * var(--y)) solid red;
  border-left:calc(1px * var(--x)) solid green;
  height:50px;
}
<body>
  <div class="y">
    <div class="x">
      <div class="y">
        <div class="x">
          <div class="y">
            <div class="x">
              <div class="y result">

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

If you inspect the element you will find for the last element that border-right is equal to 17px (10 + 7) and border-left is equal to 16px (10 + 6)

This idea fits nicely in elements with a 2 level structure, like lists:

body {
  --x: 30;
}

ul { 
    font-size: calc(var(--x) * 1px);
    --y: calc(var(--x) - 8);
}

li {
  --x: calc(var(--y));
}
  <ul>level A
    <li>item 1
    </li>
    <li>item 2
      <ul>level B
        <li>item 2.1
          <ul>level C
            <li>item 2.1.1
            </li>
            <li>item 2.1.2
            </li>
          </ul>
        </li>
        <li>item 2.2
        </li>
      </ul>
    </li>
  </ul>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!