是否可以在 CSS 中的 calc 中使用子索引?

Is it possible to use child index in calc in CSS?

我想要实现的是通过将颜色值乘以子索引,使每个子具有与前一个不同的颜色(结果将类似渐变)。

伪代码:

.parent > div:nth-child() {
    background-color: rgb(index * 10, 255, 255);
}

注意:此答案不使用基本 CSS,而是显示了使用 SASS @for 循环以避免手写每个规则的示例。如果OP没有GULP或其他方式编译SASS/SCSS,有在线编译器如SassMeister or using CodePen,更改CSS框上的设置以添加预处理器:

然后查看编译好的CSS:

@for $i from 1 to 12 {
    .parent > div:nth-child( #{$i}) {
        background-color: rgb($i * 20, 255, 255);
    }
}

您可以输入 children 的总数作为最后一个值(本例中的 12。这将输出:

.parent > div:nth-child(1) {
  background-color: #14ffff;
}

.parent > div:nth-child(2) {
  background-color: #28ffff;
}

.parent > div:nth-child(3) {
  background-color: #3cffff;
}

.parent > div:nth-child(4) {
  background-color: #50ffff;
}

.parent > div:nth-child(5) {
  background-color: #64ffff;
}

.parent > div:nth-child(6) {
  background-color: #78ffff;
}

.parent > div:nth-child(7) {
  background-color: #8cffff;
}

.parent > div:nth-child(8) {
  background-color: #a0ffff;
}

.parent > div:nth-child(9) {
  background-color: #b4ffff;
}

.parent > div:nth-child(10) {
  background-color: #c8ffff;
}

.parent > div:nth-child(11) {
  background-color: #dcffff;
}

作为解决方案之一,您可以直接从JavaScript 中赋值。但是如果你真的想通过CSS来管理这个,那么你可以强制元素使用JS设置索引和CSS Variables and using calc()在CSS规则中进行必要的计算。 示例如下:

document.querySelectorAll('.parent > div').forEach((el, index) => el.style.setProperty('--custom-index', index));
.parent > div {
  height: 50px;
  width: calc(30px + 50px * (var(--custom-index) * 0.5));
  margin-top: 5px;
  background-color: rgb(calc(var(--custom-index) * 10), calc(var(--custom-index) * 40), calc(var(--custom-index) * 50));
}
<div class="parent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

但是如果你删除或添加元素,那么在这种情况下你将需要re-runJS示例中提供的脚本重新计算。