我希望通过将颜色值乘以子索引来实现每个子元素的颜色都与前一个不同(结果将类似于渐变)。
伪代码:
.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/