htmlcsscss-calc

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


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);
}

Solution

  • NOTE: This answer does NOT use basic CSS, but rather shows an example of using a SASS @for loop to avoid handwriting each rule. If OP does not have GULP or another way to compile the SASS/SCSS, there are online compilers such as SassMeister or using CodePen, changing the settings on the CSS box to add a preprocessor:

    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;
    }