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

标签 html css css-calc

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

伪代码:

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

最佳答案

作为解决方案之一,您可以直接从 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示例中提供的脚本来重新计算。

关于html - 是否可以在 CSS 的 calc 中使用子索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70915932/

相关文章:

java - 那里有任何 Ajax 窗口框架吗?

html - 为什么我的 div 或导航栏没有一直向右延伸?

CSS Calc - 总是达到 '0' 或 '1'

javascript - 如何根据另一个输入的值进行输入?

html - 去除覆盖4列产品的白色背景

javascript - Google Nexus 网站中使用的 JS 插件的名称

css - 侧边栏宽度问题

html - 使用 calc() 时,宽度继承不会填充父级

css - 为什么 CSS calc() 函数不起作用?

html - 跨度 css 无法正常工作