【问题标题】:Is it possible to use child index in calc in CSS?是否可以在 CSS 的 calc 中使用子索引?
【发布时间】:2022-01-31 06:39:42
【问题描述】:

我希望通过将颜色值乘以子索引来实现每个子节点的颜色与前一个子节点的颜色不同(结果将类似于渐变)。

伪代码:

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

【问题讨论】:

  • 为此使用 Sass 循环,你不能使用 CSS
  • 你提前知道有几个孩子吗?
  • @T.J.Crowder 是的,我知道孩子的数量
  • 那么你可以制定与孩子一样多的规则,每个规则都有一个明确的数字。 Sass 循环只会生成它。

标签: html css css-calc


【解决方案1】:

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

然后查看编译后的 CSS:

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

您可以输入孩子的总数作为最后一个值(在本例中为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;
}

【讨论】:

    【解决方案2】:

    作为解决方案之一,您可以直接从 JavaScript 赋值。但是如果你真的想通过 CSS 来管理这个,那么你可以强制元素使用 JS 和CSS Variables 设置索引,并使用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>

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

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 2015-01-31
      • 2017-04-13
      • 2016-08-30
      • 2012-12-17
      • 2016-11-07
      • 2018-10-17
      • 2012-10-21
      • 1970-01-01
      相关资源
      最近更新 更多