Home > Back-end >  Is it possible to use child index in calc in CSS?
Is it possible to use child index in calc in CSS?

Time:01-31

What I'm looking to achieve is each child having a diffrent color than the previous one (result would be gradient-like) by multiplying the color value with the child index.

Pseudo-code:

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

CodePudding user response:

As one of the solutions, you can assign values directly from JavaScript. But if you really want to manage this through CSS, then you can force the elements to set indexes using JS and enter image description here

And then viewing the compiled CSS:

enter image description here

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

You can enter the total number of children as the last value (the 12 in this example. This will output:

.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;
}
  •  Tags:  
  • Related